24

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.

5
  • 2
    I don't see any a tag in your code Commented Oct 18, 2013 at 6:55
  • Works in this fiddle: jsfiddle.net/2A3Uf Commented Oct 18, 2013 at 6:55
  • @user1671639, i've updated my question with the img reference. Commented Oct 18, 2013 at 7:20
  • @RGraham, that basically renders that into the DOM which is something im not looking for. I should have been more explicit. I've updated the question. Commented Oct 18, 2013 at 7:24
  • Probably too late to be of use, but can you not just wrap HTMLSTRING in a <p> before you make it a jQuery object? Commented Oct 18, 2013 at 22:23

2 Answers 2

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/

Sign up to request clarification or add additional context in comments.

Comments

18

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

4 Comments

Nikhil, which version of jQuery has the parseHTML. I can only see the parseJSON and parseXML API's as part of my jQuery.
ok looks like i don't get have the parseHTML as part of my jQuery (1.8.0-min.js). Any other ways to go about this?
I can see parseHTML function in 1.8.0 source..code.jquery.com/jquery-1.8.0.js
Hi, it's maybe a silly question, but how to get html string back ?

Your Answer

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.