Home > OS >  Add a class in javascript without targeting the parent element
Add a class in javascript without targeting the parent element

Time:01-05

I have a problem with this piece of code:

document.querySelector('.location__list-link[data-area-id="' areaId '"]').parentElement.classList.add("plop");

I actually want to add the "plop" class to ".location__list-link" but I have a second class behind it. This last class should not be taken into account.

The HTML is :

<div >
  <div >
    <ul >
      <li ><a data-area-id="1"  href="https://www.antibes-juanlespins.com/">Antibes Juan-les-Pins</a></li>
      <li  ><a data-area-id="22"  href="http://bezaudun.fr/">Bézaudun-les-Alpes</a></li>
      <li  ><a data-area-id="3"  href="https://www.biot.fr/">Biot</a></li>
      <li ><a data-area-id="21"  href="https://bouyon.fr/">Bouyon</a></li>
    </ul>
  </div>
</div>

And I don't know how to add a second class to my selection or what to do about .parentElement because when I delete it it doesn't work at all. Thank you in advance :)

CodePudding user response:

Just remove parentElement and it works as one would expect. You can completely ignore the other class listed on the element:

const areaId=3
document.querySelector('.location__list-link[data-area-id="' areaId '"]').classList.add("plop");
.plop{ background-color:red}
<div >
  <div >
    <ul >
      <li ><a data-area-id="1"  href="https://www.antibes-juanlespins.com/">Antibes Juan-les-Pins</a></li>
      <li ><a data-area-id="22"  href="http://bezaudun.fr/">Bézaudun-les-Alpes</a></li>
      <li ><a data-area-id="3"  href="https://www.biot.fr/">Biot</a></li>
      <li ><a data-area-id="21"  href="https://bouyon.fr/">Bouyon</a></li>
    </ul>
  </div>
</div>

  •  Tags:  
  • Related