1

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

asked Sep 14, 2016 at 7:51
10
  • Could you please give an example of the output you're expecting to see Commented Sep 14, 2016 at 7:53
  • @RoryMcCrossan updated the question Commented Sep 14, 2016 at 7:54
  • Add .toString()? Commented Sep 14, 2016 at 7:55
  • tried but it shows [object HTMLSpanElement] @ThisNameBetterBeAvailable Commented Sep 14, 2016 at 7:56
  • What exactly you want to do? console.log element or work with this element? Commented Sep 14, 2016 at 7:59

2 Answers 2

1

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");
});
answered Sep 14, 2016 at 8:05

1 Comment

yeah, but does it matter? are you gonna process it later on?
0

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 ");
answered Sep 14, 2016 at 8:20

2 Comments

It doesn't wrap text in html
Not sure what you mean by "wrap text in html". If you want the text elements, use .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.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.