[英]Get ID of parent input div with nested radio buttons for accessibility
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).我希望子单选按钮在 label 中引用其父级(出于可访问性原因)。 I am planning on using aria-labelledby
to do this.我打算使用aria-labelledby
来做到这一点。
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.我最大的问题是单选按钮是动态生成的,所以我需要能够弄清楚父 ID 是什么。
Currently, the layout of the html looks like this:目前,html 的布局如下:
<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.在创建单选按钮时会传入choiceId 和 level。
I want each child to reference its parent when the label is read by the screenreader.当屏幕阅读器读取 label 时,我希望每个孩子都参考其父母。
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"因此,对于id="level-child-1"
的<input>
标签,它会说“leash, blue”,而对于id="level-child-0"
的<input>
标签,它会说,“cat, leash "
Is there a way to grab the parent input id?有没有办法获取父输入ID? I looked into using something like const parentInput = document.getElementById("label").parentNode.nodeName;
我研究过使用类似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?它可以在节点上 go 直到找到父input
组件的 id 吗?
Here is a basic jsfiddle with a working nested radio button: http://jsfiddle.net/wgoLxanc/ so I at least have the concept figured out.这是一个带有工作嵌套单选按钮的基本 jsfiddle: http://jsfiddle.net/wgoLxanc/所以我至少弄清楚了这个概念。 The tricky thing is figuring out how to get the parent id.棘手的事情是弄清楚如何获取父ID。
To get an unknown ID of a parent element:获取父元素的未知 ID:
Vanilla Javascript:香草 Javascript:
One level up:上一级:
document.querySelector("YOUR-ELEMENT-SELECTOR").parentNode.id;
Two levels up:上两层:
document.querySelector("YOUR-ELEMENT-SELECTOR").parentNode.parentNode.id;
jQuery: jQuery:
One level up:上一级:
$("YOUR-ELEMENT-SELECTOR").parent().attr("id");
Two levels up:上两层:
$("YOUR-ELEMENT-SELECTOR").parent().parent().attr("id");
use data attribute in the radio button to save the parent ID.使用单选按钮中的数据属性来保存父 ID。
see: how to get parent div data-attribute javascript请参阅: 如何获取父 div 数据属性 javascript
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.