user1954135
user1954135

Reputation: 25

How to add a class to element if another element is empty?

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

Answers (4)

brk
brk

Reputation: 50326

Use .text() to find if it is empty

var a =$(".info").text().trim();
a===""?($("#title").removeClass("blue").addClass('red')):''

JSFIDDLE

Upvotes: 5

Albert Israel
Albert Israel

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

Shaunak D
Shaunak D

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

guradio
guradio

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

Related Questions