[jquery] parse html string with 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?

This question is related to jquery

The answer is


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.


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.


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