Reputation: 429
I created a list (li) and I want to add a specific class to that list
<ul class="main">
<li></li>
<li>
<span class="ext"></span>
<ul>
<li>
<span class="ext"></span>
</li>
</ul>
<li>
</ul>
I want to add a class to only that first ul > second li > first span
class but for some reasons it is also adding it to that span class under the second ul.
This is the code I'm using to add the class
$('ul.main li:nth-child(2) .ext').addClass('another-ext')
Snippet:
$('ul.main li:nth-child(2) .ext').addClass('another-ext')
.another-ext {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="main">
<li></li>
<li>
<span class="ext"></span>
<ul>
<li>
<span class="ext">hello</span>
</li>
</ul>
<li>
</ul>
Upvotes: 0
Views: 37
Reputation: 27082
Use children selector. It should work.
$('ul.main > li:nth-child(2) > .ext').addClass('another-ext')
.another-ext {color: red}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="main">
<li>A</li>
<li>
<span class="ext">B</span>
<ul>
<li>
<span class="ext">C</span>
</li>
</ul>
<li>D
</ul>
Upvotes: 2