Rebaz Salih Rebaz Salih - 5 months ago 9
CSS Question

Add classes to parent nodes (<a>) in a nested list

The

<a>
inside the last
<li>
of the innermost
<ul>
has a class which is named
current
. It highlights the active link.

I want to highlight all links that are parents from this link.

HTML

<ul>
<li>
<a href="a.html">Samsung</a>
<ul>
<li>
<a href="b.html">Galaxy</a>
<ul>
<li>
<a href="c.html">Galaxy Note 4</a>
</li>
<li>
<a href="c.html" class="current">Galaxy S 5</a>
</li>
</ul>
</li>
</ul>
</li>
</ul>


Galaxy S 5 has the class
current
, but I also want to add the class
current
to the parent links (Samsung, Galaxy).

Answer
  1. Define an outermost parent element by giving it an id.
  2. Get the element with the current class and assign it to a temp var.
  3. Loop over the elements starting with your current element and change the value of the temp var to temp.parentNode. If the elements parent node is a list item add your current class to the first child element of the list element.

var until = document.getElementById("list"),
    crnt = document.getElementsByClassName('current'),
    tmp = crnt.item(0);

while(tmp !== until) {
  if(tmp.tagName === "LI") {
    tmp.children.item(0).classList.add("current");
  }
  tmp = tmp.parentNode;
}
.current {
  color: tomato;
}
<ul id="list">
  <li>
    <a href="a.html">Samsung</a>
    <ul>
      <li>
        <a href="b.html">Galaxy</a>
        <ul>
          <li>
            <a href="c.html">Galaxy Note 4</a>
          </li>
          <li>
            <a href="c.html" class="current">Galaxy S 5</a>
          </li>
        </ul>
      </li>
    </ul>
  </li> 
</ul>