Reputation: 2101
I am trying to change the background (and other styles) of a div if it has a specific child. I am using .length to check if the specific child exists but even if it doesn't the div is taking the styles from the jquery if statement. My HTML:
<div class="full-text-panel">
<div class="main-wrap">
<h1 class="home-h1">This is a header</h1>
<a class="body-button">This is a button</a>
</div><!--end main-wrap-->
</div><!--end full-text-panel-->
And my jQuery:
var fullText = $('.full-text-panel');
var bodyButton = $('.body-button');
if ( $(".full-text-panel .body-button").length > 0 ) {
fullText.css("background", "red");
} else {
fullText.css("background", "blue");
}
I thought this would work, but both fullText panels are taking the background red style. What am I doing wrong?
Upvotes: 0
Views: 1447
Reputation: 15393
In your context iterate with each in jquery
$('.full-text-panel').each(function() {
if($(this).find('a.body-button').length > 0){
$(this).css("background", "red");
}
else{
$(this).css("background", "blue");
}
});
Upvotes: 1
Reputation:
$(function(){
$('.full-text-panel:has(.body-button)').addClass('red');
});
.full-text-panel{
background:blue;
}
.red{
background:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="full-text-panel">
<div class="main-wrap">
<h1 class="home-h1">This is a header</h1>
<a class="body-button">This is a button</a>
</div><!--end main-wrap-->
</div><!--end full-text-panel-->
<div class="full-text-panel">
<div class="main-wrap">
<h1 class="home-h1">This is a header</h1>
</div><!--end main-wrap-->
</div><!--end full-text-panel-->
Upvotes: 3