Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert HTML string into Jquery Object

Tags:

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.

like image 491
user320550 Avatar asked Oct 18 '13 06:10

user320550


2 Answers

$.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/

like image 51
Renan Araújo Avatar answered Oct 03 '22 20:10

Renan Araújo


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

like image 33
nik Avatar answered Oct 03 '22 22:10

nik