Reputation: 59
I want to addClass to previous div.local_text if there is an < img> tag inside div.local_logo
<div>
<div class="local_text"></div>
<div class="local_logo">
<a href="#"></a>
</div>
</div>
So far this is not working, is adding class to all div.local_text
but the previous only.
if (jQuery(".local_logo:has(img)")) {
jQuery(".local_logo").prev(".local_text").addClass("half");
};
Upvotes: 0
Views: 4151
Reputation: 498
try this (use .find()
method )
$('.local_logo div').each(function() {
if ($(this).find('img').length) {
// there is an image in this div, do anything here..
}
});
it works for me, hope to solve your problem too :)
Upvotes: 0
Reputation: 87203
Use :has()
selector
Selects elements which contain at least one element that matches the specified selector.
jQuery(".local_logo:has(img)") // Select all the classes `.local_logo` having img as descendent
.prev(".local_text").addClass("half");
jQuery(".local_logo:has(img)").prev(".local_text").addClass("half");
.half {
background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<div class="local_text">First</div>
<div class="local_logo">
<img src="" alt="">
</div>
</div>
<div>
<div class="local_text">Second</div>
<div class="local_logo">
<a href="#"></a>
</div>
</div>
<div>
<div class="local_text">Third</div>
<div class="local_logo">
<img src="" alt="">
</div>
</div>
Upvotes: 2
Reputation: 253308
I'd suggest:
// cache the <div clas="local_text"> elements:
var text = jQuery('.local_text');
// use toggleClass() with a class-name and switch,
// the class-name will be applied to the relevant elements
// if the switch returns a truthy value (0 is falsey):
text.toggleClass('half', text.next('div.local_logo').find('img').length);
Note that the question title says you want to add a class if the next <div>
contains an <img>
element, whereas the code in the question has <a>
element.
If there's a mistake somewhere, please adjust the selector within find()
as appropriate.
References:
Upvotes: 2