Reputation: 767
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?
Upvotes: 60
Views: 105657
Reputation: 5345
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.
Upvotes: 1
Reputation:
just add container element befor your img element just to be sure that your intersted element not the first one, tested in ie,ff
Upvotes: 1
Reputation:
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.
Upvotes: 2
Reputation: 35667
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")
Upvotes: 107