Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Giving html list elements that only contain a specified text a background color using Jquery

I have the following html script:

<ul>
<li class="container">
<div class="age">24</div>
<div class="married">no</div>
</li>

<li class="container">
<div class="age">27</div>
<div class="married">yes</div>
</li>

<li class="container">
<div class="age">56</div>
<div class="married"><!--empty--></div>
</li>

<li class="container">
<div class="age">34</div>
<div class="married">no</div>
</li>
</ul>

I would like that only the li elements that contain a no in their div.married get a green background using Jquery.

I don't understand why this code does not work. How do I get the intended result?

like image 477
Bentley4 Avatar asked Dec 04 '25 17:12

Bentley4


2 Answers

Try this:

$(".container .married").filter(function() {
    return $(this).text() == "no";
}).closest('.container').css('background-color', 'green');

Example fiddle

like image 74
Rory McCrossan Avatar answered Dec 06 '25 09:12

Rory McCrossan


You have an erroneous ; after "green" although you would still not get what your looking for.

You could also;

$(".married:contains(no)").parent().css(...)
like image 36
Alex K. Avatar answered Dec 06 '25 08:12

Alex K.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!