How to get the toplevel node of each anchor inside li in JavaScript?

56 views Asked by At

So I have my html like so:

<ul id="page-nav">
  <li class="text-muted menu-title">Navigation</li>
  <li>
    <a href="#" class="waves-effect active">
      <img src="img/archive.svg" alt="archive"><span class="menu-spans"> Dashboard </span> 
    </a>
  </li>
  <li>
    <a href="#" class="waves-effect">
      <img src="img/speech-bubble.svg" alt="speech"><span class="menu-spans"> Chat </span> 
    </a>
  </li>
  <li>
    <a href="#" class="waves-effect">
      <img src="img/gains.svg" alt="speech"><span class="menu-spans"> Gains </span> 
    </a>
  </li>
</ul>

When a user clicks on any of the element within the li, I would like to add a class to the li.

How can this be done in pure JavaScript?

My initial thought was the following:

document.getElementById("page-nav").addEventListener(
  "click", i => {
    // debug purposes
    console.log(this.parentNode);
  }
);

But it dont work.

1

There are 1 answers

2
ADH - THE TECHIE GUY On BEST ANSWER

you can do that using currentTarget in js .I'm added the snippet below(here I'm added the class .red to corresponding li when click on the sub items)

var k = document.getElementsByClassName("item");

for(i = 0 ;i < k.length; i++)
{
  
    k[i].addEventListener("click",function(event){
      var el = event.currentTarget;
      var value = el.id;
      document.getElementById(value).classList.add ("red");

    });
}
.red{
  background:red;
  }
<ul id="page-nav">
  <li class="text-muted menu-title">Navigation</li>
  <li class="item" id="one">
    <a href="#" class="waves-effect active">
      <img src="img/archive.svg" alt="archive"><span class="menu-spans"> Dashboard </span> 
    </a>
  </li>
  <li class="item" id="two">
    <a href="#" class="waves-effect">
      <img src="img/speech-bubble.svg" alt="speech"><span class="menu-spans"> Chat </span> 
    </a>
  </li>
  <li class="item" id="three">
    <a href="#" class="waves-effect">
      <img src="img/gains.svg" alt="speech"><span class="menu-spans"> Gains </span> 
    </a>
  </li>
</ul>