0

I have some custom radio buttons that are heavily nested. I would like for the child radio buttons to reference their parent in the label (for accessibility reasons). I am planning on using aria-labelledby to do this.

My biggest problem has been that the radio buttons are dynamically generated, so I need to be able to figure out what the parent id is.

Currently, the layout of the html looks like this:

<div ...
  <input id="cat" name="level-parent" type="radio" value="cat" />
  <label for="cat" />
  <div>
    <div ...
    <div ...
     <div
     <div ...
       <input name="level-child-0" id=
leash" type="radio" value="leash">
       <label />
         <div ...
          <div ...
             <div ...
                <input name="level-child-1" id=
"blue" type="radio" value="blue">
                <label />
                
                
              

The inputs and labels are all generated by the same component that is mapped over.

<input
          type="radio"
          name={`level-${level}`}
          value={choiceId}
          id={choiceId}
          aria-labelledby={}
        />
        <label htmlFor={choiceId} />

The choiceId and level are passed in as the radio buttons are being created.

I want each child to reference its parent when the label is read by the screenreader.

So for the <input> tag with id="level-child-1" it would say "leash, blue" and for the <input> tag with id="level-child-0" it would say, "cat, leash"

Is there a way to grab the parent input id? I looked into using something like const parentInput = document.getElementById("label").parentNode.nodeName; but the problem is that I don't know the id of the parent. Can it go up the nodes until it find the id of the parent input component?

Here is a basic jsfiddle with a working nested radio button: http://jsfiddle.net/wgoLxanc/ so I at least have the concept figured out. The tricky thing is figuring out how to get the parent id.

jenryb
  • 2,017
  • 12
  • 35
  • 72

2 Answers2

1

To get an unknown ID of a parent element:

Vanilla Javascript:

One level up:

document.querySelector("YOUR-ELEMENT-SELECTOR").parentNode.id;

Two levels up:

document.querySelector("YOUR-ELEMENT-SELECTOR").parentNode.parentNode.id;

jQuery:

One level up:

$("YOUR-ELEMENT-SELECTOR").parent().attr("id");

Two levels up:

$("YOUR-ELEMENT-SELECTOR").parent().parent().attr("id");
Josh
  • 3,872
  • 1
  • 12
  • 13
0

use data attribute in the radio button to save the parent ID.

see: how to get parent div data-attribute javascript