Behseini Behseini - 3 months ago 7
jQuery Question

Not Able to Select a in Lists which Has not child

Can you please let me know whoe to select only parents

<a>
elements and not the child list in item 2?

What I want to do is adding
.red
class to only the first layer of
<a>
in items 1 to 5 and not to sub
<a>
s in item2



$(".the-list a:not(:has(ul))> a").each(function() {
$(this).addClass('red');
});

.red{color:red;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="the-list">
<ul>
<li><a>Item 1</a></li>
<li><a>Item 2</a>
<ul>
<li><a>Item 2-1</a></li>
<li><a>Item 2-2</a></li>
<li><a>Item 2-3</a></li>
<li><a>Item 2-4</a></li>
<li><a>Item 2-5</a></li>
</ul>
</li>
<li><a>Item 3</a></li>
<li><a>Item 4</a></li>
<li><a>Item 5</a></li>
<li><a>Item 6</a></li>
</ul>
</div>




Answer

> restriction will do it.

$(".the-list > ul > li > a").each(function() {
    $(this).addClass('red');
});
.red{color:red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="the-list">
<ul>
  <li><a>Item 1</a></li>
  <li><a>Item 2</a>
    <ul>
      <li><a>Item 2-1</a></li>
      <li><a>Item 2-2</a></li>
      <li><a>Item 2-3</a></li>
      <li><a>Item 2-4</a></li>
      <li><a>Item 2-5</a></li>
    </ul>
  </li>
  <li><a>Item 3</a></li>
  <li><a>Item 4</a></li>
  <li><a>Item 5</a></li>
  <li><a>Item 6</a></li>
</ul>
</div>

Comments