JQuery The length of the element (s) inside each () function

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 supposed to count the number of IMG elements within a particular DIV and change the CSS 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 work inside every function.

+3
source share
3 answers

it seems to work, but here is some kind of alternative code that filters out any div with img daughters.

$('div.news_item').not(function(index){return $(this).find('img').length > 0;}).each(function(index, elem){
     $(this).css('background-color', '#cccccc');
});
+1
source

try $(this).find('img').length

+1
source

Your code is ok. Make sure you don’t have invalid HTML or you see and display the image incorrectly in the sibling element.

0
source

Source: https://habr.com/ru/post/1794195/


All Articles