如何获取id值并将其添加为祖父母作为属性

时间:2019-02-20 20:05:42

标签: javascript jquery

大家好,我先在这里发布信息,我正在导航栏上,需要为ul添加id和id,然后在其上方的锚标记中添加aria-controls = id的值的属性我为ul做的。

<li class="hs-menu-item hs-menu-depth-1 hs-item-has-children" role="menu">
<a href="https://www.website.org/"  aria-expanded="false">Rates</a>
<a class="child-trigger"><span></span></a>
<ul class="hs-menu-children-wrapper">

到目前为止,我已经添加了id并使用Javascript添加了属性。

document.getElementsByClassName("hs-menu-children-wrapper")[0].setAttribute("id","Rates");
document.getElementsByTagName("a")[10].setAttribute("aria-controls","Rates");

这给了我我想要的东西。

<a href="https://www.website.org" aria-expanded="false" aria-controls="Rates">Rates</a>
<a class="child-trigger"><span></span></a>
<ul class="hs-menu-children-wrapper" id="Rates" >

但是我还有其他5个ID为ID的元素,我需要将此元素应用于这些元素,并且针对不同的锚定标记,它不适用于我们计划与其一起使用的每个页面。我非常需要帮助来简化此感谢。

1 个答案:

答案 0 :(得分:0)

因此,假设每个元素都包含在其自己的父元素中,则类似的方法可能会起作用。当然,您需要为触发器a提供某种类型的类,以供识别和使用。

/**
 * First, we create a list of all the uls we want to connect.
 *  Note that, because some browsers don't treat a list of 
 *  nodes as an Array, we want to convert it to an array.
 *  Here, I'm using the ES6 spread operator, which may not be
 *  the best option, but for demonstration purposes, it works.
 **/
const ulEls = [...document.querySelectorAll("ul")];

/**
 * Now, iterate over that array. With each ul, we want to find
 *  a parent element, and then within that, locate the anchor
 *  that will be made the control for this ul. Once we find
 *  that, we can assign it the attribute with the value we want.
 **/
ulEls.forEach( (ulEl) => {
  let container = ulEl.parentNode,
      triggerEl = container.querySelector(".ul-controller");
      triggerEl.setAttribute("aria-controls", ulEl.id);
} );
<div>
  <a class='ul-controller' href="https://www.website.org" aria-expanded="false">Rates</a>
  <a class="child-trigger"><span></span></a>
  <ul class="hs-menu-children-wrapper" id="Rates" >
    ...
  </ul>
</div>
<div>
  <a class='ul-controller' href="https://www.website.org" aria-expanded="false">Sizes</a>
  <a class="child-trigger"><span></span></a>
  <ul class="hs-menu-children-wrapper" id="Sizes" >
    ...
  </ul>
</div>
<div>
  <a class='ul-controller' href="https://www.website.org" aria-expanded="false">Times</a>
  <a class="child-trigger"><span></span></a>
  <ul class="hs-menu-children-wrapper" id="Cheezburger" >
    ...
  </ul>
</div>

如果打开控制台,您会看到aria-controls是动态设置的。基本上,它会对每个ul进行迭代,并以此为起点,使用a将其同级aria-controls设置为适当的setAttribute()

编辑:如前所述,querySelectorAll返回一个nodeList,并不是每个浏览器都将其视为一个数组。因此,最佳实践是在尝试对集合运行forEach之前将其转换为数组。