parse html string with jquery

Jquery

Jquery Problem Overview


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?

Jquery Solutions


Solution 1 - Jquery

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")

Solution 2 - Jquery

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 whole html block from data into #fullHtmlOutput and the src of the image into #imgSrc.

Solution 3 - Jquery

just add container element befor your img element just to be sure that your intersted element not the first one, tested in ie,ff

Solution 4 - Jquery

One thing to note - as I had exactly this problem today, depending on your HTML jQuery may or may not parse it that well. jQuery wouldn't parse my HTML into a correct DOM - on smaller XML compliant files it worked fine, but the HTML I had (that would render in a page) wouldn't parse when passed back to an Ajax callback.

In the end I simply searched manually in the string for the tag I wanted, not ideal but did work.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMarvinSView Question on Stackoverflow
Solution 1 - JqueryfalstroView Answer on Stackoverflow
Solution 2 - JquerySeanView Answer on Stackoverflow
Solution 3 - JqueryzanoonView Answer on Stackoverflow
Solution 4 - JqueryThe CoderView Answer on Stackoverflow