0

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.

0

4 Answers 4

5

Use .text() to find if it is empty

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

JSFIDDLE

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this worked perfectly for me and was quite easy to adjust.
3

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>

Comments

0

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

Comments

0

: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");

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.