March 20, 2012
Get & format HTML tags from a simple string
Question by MicroEyes
I have a String variable say
strHTML = "<div class='abc'> This is a test <span class='xyz'> String </span> </div> "
that i m receiving from server. When I use
$('#container').append(strHTML);
it is displaying the whole string including HTML tag in “container”.
What i want is to take each HTML tag as HTML element in “Container” & apply class whever i defined in it..
Answer by MicroEyes
I did this working…
Actually, what i did is..
var strHTML = "<div class='abc'> This is a test <span class='xyz'> String </span> </div> ";
$("#container").html(strHTML);
Thankx to all for helping me..
Answer by Starx
Split your string and change them into DOM Object. Then you can manipulate them as you want.
Example:
var abcDiv = $("<div></div>");
abcDiv.attr('class', 'abc'); // add class
var xyzSpan= $("<span></span>");
xyzSpan.attr('class', 'xyz'); //add class
abcDiv.append("This is a test"); //Add the text
abcDiv.append(xyzSpan); //Add the span
$('#container').append(abcDiv); //insert the div