Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery .length of element(s) inside each() function

Tags:

jquery

Assuming I have the following HTML

<div class="news_item">
    <div class="news_content">Some Content Here...</div>
    <img src="something.jpg" />
</div>

I have the following JQuery code; which is suppose to count how many IMG elements there are within the particular DIV and change the CSS of DIV.news_content if there are no IMG elements.

$('div.news_item').each(function() {
        if ($('img', this).length == 0) {
        $('div.news_content', this).css('background-color', '#cccccc');
    }
});

However $('img', this).length does not seem to work inside the each function.

like image 319
sidewinder Avatar asked Jun 23 '26 06:06

sidewinder


1 Answers

it sounds like it's working, but here is some alternative code that filters out any div's with img children.

$('div.news_item').not(function(index){return $(this).find('img').length > 0;}).each(function(index, elem){
     $(this).css('background-color', '#cccccc');
});
like image 70
DefyGravity Avatar answered Jun 25 '26 20:06

DefyGravity



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!