I have a HTML tag as a string comes from controller.. I need to parse it in html..The code is like ,
var str = '<span id="c.s.y"></span> Y <span id="c.s.m"></span> M';
var parsed = $.parseHTML(str);
This parsed string into html.. but I have to append some text before each seperate tag..I fetch each tag as,
$.each( parsed , function( i, el ) { console.log("asd" + el + "asd"); });
I cann't append text in each tag here it shows [object HTMLSpanElement]
[object Text]
.. how to append text here..
I want output as a
asd <span id="c.s.y"></span> asd
asd Y asd
asd <span id="c.s.m"></span> asd
asd N asd
2 Answers 2
For HTML elements you could use outerHTML
property
$.each(parsed, function(i, el) {
var $el = $(el);
if ($el.prop('outerHTML'))
console.log("asd" + $el.prop('outerHTML') + "asd");
else
console.log("asd" + $el.text() + "asd");
});
1 Comment
To get your html into something you can work with, use this:
$("<div/>").html(txt);
eg, in your case:
var str = '<span id="c.s.y"></span> Y <span id="c.s.m"></span> M';
var parsed = $("<div/>").html(str);
you then have 'parsed' as a 'normal' jquery object which you can manipulate as required, eg:
parsed.find("*").wrap("<span>");
parsed.contents().wrap("<span>");
$("#myid").append(parsed);
As .wrap()
applies tags, in your case, you'll need to use .append
and .prepend
, something like:
parsed.find("*").andSelf().append(" asd ").prepend(" asd ");
2 Comments
.contents()
. Manipulate as required - the question was how to parse a string as html and append some text before each seperate tag - nothing about wrapping text.
.toString()
?[object HTMLSpanElement]
@ThisNameBetterBeAvailableconsole.log
element or work with this element?