Parse html string with jquery

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

I have something like:

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

How can I get attributes (e.g. src ) from this HTML line?

+60
jquery
Apr 01 '09 at 9:03
source share
4 answers

I am not 100% sure, but I will not

 $(data) 

create a jquery object with a DOM for this data, nowhere connected? Or, if it is already being parsed as a DOM, you can simply switch to $ ("# myImg", data) or any other selector according to your needs.

EDIT
Rereading your question, it seems that your β€œdata” is already a DOM, which means you can just go (if your DOM has only img, otherwise you will need a more accurate selector)

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

if you want to access the src attribute. If your data is just text, this will probably work

 $("img", $(data)).attr ("src") 
+106
Apr 01 '09 at 9:08
source share

Marvins.-

Try:

 $.ajax({ url: uri+'?js', success: function(data) { var imgAttr = $("img", data).attr('src'); var htmlCode = $(data).html(); $('#imgSrc').html(imgAttr); $('#fullHtmlOutput').html(htmlCode); } }); 

This should load the entire html block from the data in #fullHtmlOutput and src image in #imgSrc.

+2
Jul 01 '09 at 20:12
source share

just add a container element for your img element to make sure your interstitial element is not the first one checked, e.g. ff

+1
Jul 11 '09 at 21:16
source share

One thing to note is that since I had exactly this problem today, depending on your jQuery HTML, parsing may or may not be. jQuery will not parse my HTML in the correct DOM - it worked fine on small XML-compatible files, but the HTML that I had (which would display on the page) would not be parsed by the Ajax callback.

In the end, I just searched manually in the string for the tag that I wanted, but not perfect, but worked.

+1
Mar 31 2018-12-12T00:
source share



All Articles