Reputation: 25
I am trying to remove the existing class (blue) and add a new class (red) to the <'h2'> when the <'a'> is empty.
<div id="heading" class="header">
<h2 id="title" class="blue">Header text goes here</h2>
<a class="info" href="#"></a>
</div>
<style>
.blue{color:blue}
.red{color:red}
</style>
I have tried a few variations but without success. This is my latest.
$("#heading a.info:empty").removeClass('blue').addClass("red");
Any help on this would be appreciated.
Upvotes: 0
Views: 218
Reputation: 50326
Use .text()
to find if it is empty
var a =$(".info").text().trim();
a===""?($("#title").removeClass("blue").addClass('red')):''
Upvotes: 5
Reputation: 585
if($("#heading a.info").text() === ''){
$("#heading h2").removeClass('blue').addClass("red");
}
.blue{color:blue}
.red{color:red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="heading" class="header">
<h2 id="title" class="blue">Header text goes here</h2>
<a class="info" href="#"></a>
</div>
Upvotes: 3
Reputation: 20636
:empty
returns a collection of elements. And you need to add/remove class from h2
,
so use .prev()
to get the previous sibling.
$("#heading a.info:empty")
.prev('#title')
.removeClass('blue')
.addClass("red");
Upvotes: 0
Reputation: 15555
if ($("#heading a.info:empty")) {
$("#title").removeClass('blue').addClass("red");
}
.blue {
color: blue
}
.red {
color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="heading" class="header">
<h2 id="title" class="blue">Header text goes here</h2>
<a class="info" href="#"></a>
</div>
Should remove from h2
not from anchor
Upvotes: 0