22

I have a HTML string which is a mix of text plus HTML tags, which i'm trying to convert into an object. So for e.g. my HTML string would look like:

Pay using your <img src="visa-src" /> or your <img src="mc-src" />

I'm using jquery 1.8.0 and tried using $(HTMLSTRING) however for some reason it strips out the text before the anchor and gives the rest, i.e. object with the children #img, #text and #img while the first text (Pay using your) gets stripped off

However lets say if the input is:

<img src="visa-src" /> or your <img src="mc-src" />

it correctly gives me the object with three child elements in it #img, #text and #img.

Are there any other ways to convert this properly?

Update: What i'm ultimately looking at is to change the each of the img src there in the HTML string and prepend with some host there.

Thanks.

user320550
  • 1,093
  • 6
  • 20
  • 37

2 Answers2

33

$.parseHTML() parses a string into an array of DOM nodes.

To create the object you need to add $():

$($.parseHTML(yourString))

Take a look at this fiddle: http://jsfiddle.net/j05ucnfv/

Reference: http://api.jquery.com/jQuery.parseHTML/

Renan Araújo
  • 3,533
  • 11
  • 39
  • 49
16

Use

$.parseHTML()

instead of

$(HTMLSTRING)

See below JS Code..

var HTMLSTRING = 'Pay using your <img src="visa-src" /> or your <img src="mc-src" />';

var HTMLSTRING1 = '<img src="visa-src" /> or your <img src="mc-src" />';

console.log($.parseHTML(HTMLSTRING));
console.log($.parseHTML(HTMLSTRING1));

Demo Fiddle

aksu
  • 5,221
  • 5
  • 24
  • 39
Nikhil N
  • 4,507
  • 1
  • 35
  • 53