Freddy
Freddy

Reputation: 867

addClass() to direct child only (and not nested elements)

I have the following markup:

<div class="menu">
  <a href="#" class="dropdown-item">Link 1</a>
  <a href="#" class="dropdown-item">Link 2</a>
  
  <ul class="hamburgerMenu__menu--levelTwo">
    <li><a href="#" class="dropdown-item">Link 1</a></li>
    <li><a href="#" class="dropdown-item">Link 2</a></li>
  </ul>
  
</div>

What I'm trying to do, via JQuery, is to add the class remove to the a tags that are outside the ul. So I'm trying to achieve the following markup:

<div class="menu">
  <a href="#" class="dropdown-item remove">Link 1</a>
  <a href="#" class="dropdown-item remove">Link 2</a>
  
  <ul class="hamburgerMenu__menu--levelTwo">
    <li><a href="#" class="dropdown-item">Link 1</a></li>
    <li><a href="#" class="dropdown-item">Link 2</a></li>
  </ul>
  
</div>

To achieve the above, I have tried the following:

$('.menu').children("a").addClass("remove");

However, the above adds remove to all the anchor tags, evevn the one's in the ul.

How can I only add remove to the a tags outside of the ul

Upvotes: 2

Views: 119

Answers (1)

EugenSunic
EugenSunic

Reputation: 13703

Use > symbol to target immediate children and you don't need jquery for that, plain js is enough.

document.querySelectorAll('.menu > a').forEach(link => link.classList.add("remove"))
<div class="menu">
  <a href="#" class="dropdown-item remove">Link 1</a>
  <a href="#" class="dropdown-item remove">Link 2</a>

  <ul class="hamburgerMenu__menu--levelTwo">
    <li><a href="#" class="dropdown-item">Link 1</a></li>
    <li><a href="#" class="dropdown-item">Link 2</a></li>
  </ul>

</div>

Upvotes: 3

Related Questions