Reputation: 5237
I am trying to delete a span class from a HTML string using Jquery. My HTML string looks like this:
<li class="left clearfix"><span id="userAvatar" class="chat-img pull-left"><img src="http://placehold.it/50/55C1E7/fff&text=U" alt="User Avatar" class="img-circle"></span><div class="chat-body clearfix"><div class="header"><strong class="primary-font">sdfsdf3424</strong></div><p>dfgfg</p></div></li>
To delete the span tag from this string I am doing the following:
var JqueryObj = $('<div/>').html(stringHTML).contents();
JqueryObj = JqueryObj.not("#userAvatar");
stringHTML = JqueryObj.html();
Where am I going wrong? Also is it possible to change the font color of the paragraph tag inside this string?
Upvotes: 0
Views: 157
Reputation: 559
here is a possible solution which explains how to remove span in a div.
var divContent = $("div").html(stringHTML);
divContent = $(divContent).find("#userAvatar").remove();
$("div").empty().html($(divContent).html());
Upvotes: 1
Reputation: 118
I am not exactly sure what you are trying to achieve so I will post a few solutions, maybe one of them will solve your problem.
1) You want to remove the a class from span#userAvatar: You should use jQuerys removeClass function.
Usage:
$( "#userAvatar" ).removeClass( "className" )
2) You want to remove the span but keep the contents: You can just replace the whole span with what's inside.
Usage:
$("#userAvatar").replaceWith(function() {
return $("img", this);
});
3) You want to remove the span class and everything that's inside it: You should use jQuery's remove() function.
Usage:
$("#userAvatar").remove();
To change the colour of the paragraph you can use jQuery's find() function.
Usage:
JqueryObj.find("p").css("color", "#EEEEEE");
Hope this helps.
Upvotes: 0
Reputation: 1839
For your first question, you should just be able to do the following:
var htmlstring = '<li class="left clearfix"><span id="userAvatar" class="chat-img pull-left"><img src="http://placehold.it/50/55C1E7/fff&text=U" alt="User Avatar" class="img-circle"></span><div class="chat-body clearfix"><div class="header"><strong class="primary-font">sdfsdf3424</strong></div><p>dfgfg</p></div></li>'
var obj = $("div").html(htmlstring);
obj.find("#userAvatar").remove();
var newhtmlstring = obj.html();
This makes a new element that has the contents of the htmlstring in it. Then, the find part finds all direct and indirect children with the selector and removes them. finally, the new html string is the contents of the temporary object we created before.
Using .find(), you can also change the font color:
obj.find("p").css("color", "red");
Upvotes: 1