开发者

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

开发者 https://www.devze.com 2023-02-12 18:16 出处:网络
Assuming I have the following HTML <div class=\"news_item\"> <div class=\"news_content\">Some Content Here...</div>

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.


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');
});


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


Your code is fine as is. Make sure you don't have invalid HTML or are looking incorrectly and spotting an image in a sibling element.

0

精彩评论

暂无评论...
验证码 换一张
取 消