brock2621
brock2621

Reputation: 35

Using jQuery to check each div for element and apply "if" statement

I'm trying to check the page and find the divs that do not have an image and change the class of an element within that div accordingly. The page is being dynamically generated so I need to check each element. The code itself works for affecting all the divs, but I need to check each one and only affect the ones with pictures.

The HTML:

<div class="container"><img width="695" height="519" src="pic123.jpg" /><div class="arrow"></div><!--arrow--></div><!--container-->
<div class="container"><div class="arrow"></div><!--arrow--></div><!--container-->

The jQuery:

$('.container').each(function(){
if ($(this).has("img")){
$('.arrow').addClass('classone');
};
});

Upvotes: 2

Views: 3036

Answers (4)

Kevin B
Kevin B

Reputation: 95048

You don't need the if statement:

$(".container:has(img) .arrow").addClass("classone");

Or you can try this version:

$(".container").filter(":has(img)").find(".arrow").addClass("classone");

Upvotes: 4

JKirchartz
JKirchartz

Reputation: 18042

try:

$('.container').each(function(){
    if ($(this).has("img")){
        $('.arrow',this).addClass('classone');
    };
});

$(this).find('.arrow').addClass('classone'); would work too

Upvotes: 1

Steve O
Steve O

Reputation: 5774

This should do the trick:

$('.container').each(function(){
   if ($("img", this).length > 0){
      $('.arrow', this).addClass('classone');
   };
});

Upvotes: 0

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

From what I understood, It should work fine If you just change

$('.arrow').addClass('classone');

to

$('.arrow', this).addClass('classone');

or Try using .has as below,

$('.container').has('img').find('arrow').addClass('classone');

Upvotes: 0

Related Questions