I would like to use Jquery to add a class to “li” element that contains a “span” element with a html/val equal to zero.
For Example if my code looks like this:
<ul>
<li><span>Item 1</span><span class="num">30</span></li>
<li><span>Item 2</span><span class="num">0</span></li>
<li><span>Item 3</span><span class="num">20</span></li>
</ul>
I want to change it to the following:
<ul>
<li><span>Item 1</span><span class="num">30</span></li>
<li class="disabled"><span>Item 2</span><span class="num">0</span></li>
<li><span>Item 3</span><span class="num">20</span></li>
</ul>
In the past I have used code to check elements attribute values, but never their html/val doing something to this effect…
$('li').has('span.num').addClass('disabled');
However in this case that would result in:
<ul>
<li class="disabled"><span>Item 1</span><span class="num">30</span></li>
<li class="disabled"><span>Item 2</span><span class="num">0</span></li>
<li class="disabled"><span>Item 3</span><span class="num">20</span></li>
</ul>
Which is obviously not going work… Thanks
This should do what you want.
JS Fiddle
I would have suggested the following:
But it doesn’t work, as it checks if the value exists inside the html — not for an exact match. In this case, each of the span.num elements have a 0 in them, so every li would get the selected class. There doesn’t seem to be an :equals() counterpart to the :contains() selector.