Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

parse html string with jquery

Tags:

jquery

I have an HTML string from a Ajax loaded source. I would like to get some attributes from an object (image) in this string, before I put the HTML into the document.

I've got something like:

$.ajax({           url: uri+'?js',           success: function(data) {              var htmlCode = $(data).html();                $('#otherObject').html(data);         }       }); 

How can I get attributes (the src for example) from this HTML string?

like image 201
MarvinS Avatar asked Apr 01 '09 09:04

MarvinS


People also ask

How to parse string jQuery?

JQuery | parseHTML() method This parseHTML() Method in jQuery is used to parses a string into an array of DOM nodes. Parameters: The parseXML() method accepts three parameter that is mentioned above and described below: data: This parameter is the HTML string to be parsed.

How do you parse text in HTML?

If you just want to parse HTML and your HTML is intended for the body of your document, you could do the following : (1) var div=document. createElement("DIV"); (2) div. innerHTML = markup; (3) result = div. childNodes; --- This gives you a collection of childnodes and should work not just in IE8 but even in IE6-7.

What is parseHTML?

parseHTML uses native methods to convert the string to a set of DOM nodes, which can then be inserted into the document. These methods do render all trailing or leading text (even if that's just whitespace).

What is .html in jQuery?

The html() Method in jQuery is used to set or return the innerHTML content of the selected element. Syntax: It returns the content of first matched element. $(selector).html() It sets the content of matched element.


1 Answers

I'm not a 100% sure, but won't

$(data) 

produce a jquery object with a DOM for that data, not connected anywhere? Or if it's already parsed as a DOM, you could just go $("#myImg", data), or whatever selector suits your needs.

EDIT
Rereading your question it appears your 'data' is already a DOM, which means you could just go (assuming there's only an img in your DOM, otherwise you'll need a more precise selector)

$("img", data).attr ("src") 

if you want to access the src-attribute. If your data is just text, it would probably work to do

$("img", $(data)).attr ("src") 
like image 131
falstro Avatar answered Oct 18 '22 09:10

falstro