user1254333
user1254333

Reputation: 23

jQuery - add html based on class name

Is there a way to add some html based on a certain class name and inject it into a specific place. The code belows shows what i am trying to do, but this is obvioulsy hard coded, i want to do it dynamically using jQuery.

<ul class="status clrfix">
<li class="green"><a href="">Completed</a><span class="arrow"></span></li>
<li class="green"><a href="">Completed</a><span class="arrow"></span></li>
<li class="blue"><a href="">In Progress</a><span class="current-stage"><img src="images/current-stage.png" /></span><span class="arrow"></span></li>
<li>Not Started <span class="arrow"></span></li>
<li class="last">Not Started <span class="arrow"></span></li>

So, essentially what i want to do is; if the class="blue" then add this inside the li:

<span class="current-stage"><img src="images/current-stage.png" /></span>

This is what i attempted, but it's not working:

$(document).ready(function() {  

if($('ul.status li').hasClass('.blue')){
    $("span.current-stage").empty().html('<img src="../images/current-stage.png" />');
}

});

Upvotes: 2

Views: 993

Answers (4)

Goran Mottram
Goran Mottram

Reputation: 6304

Try changing your if statement to the following:

if($('ul.status li').hasClass('blue')){

The hasClass() method accepts a class name as a parameter, not a selector. So you can leave out the . on the front of the class.

Also, if you wish to add HTML to without removing what is already there, use the append() function.

$("span.current-stage").append('<span class="current-stage"><img src="../images/current-stage.png" /></span>');

Upvotes: 2

odupont
odupont

Reputation: 1976

Note that you can use only CSS for the same result :

ul.status li.blue span.current-stage {
  display: inline-block;
}
ul.status li span.current-stage {
  display: none;
}

Upvotes: 0

Amritpal Singh
Amritpal Singh

Reputation: 1785

I think you should try $("span.current-stage").html(''); or you can also use .append method .

Upvotes: 0

ThdK
ThdK

Reputation: 10546

Maybe something like this?

$('ul.status li.blue span.current-stage').empty().html('<img src="../images/current-stage.png" />');      

Upvotes: 0

Related Questions