tags:

views:

33

answers:

2

I'm using and $.ajax method to get an html text. I would like to parse this html, getting the "src" from an "img" tag. I've done this way:

$.ajax({ 
    type: "GET", 
    url: "image1.html", 
    success: function(msg){                  
        var htmlCode = $(msg).html(); 
        var title = $("#immagine", htmlCode).attr("src"); 
        alert( title);
    }
});

I can get the right result from Firefox and Chrome. They alert the correct "src" value (ex: 'pics/image.jpg'). But IE return an "undefined" alert. Can someone help me? Thanks

A: 

In your code:

var htmlCode = $(msg).html(); 
var title = $("#immagine", htmlCode).attr("src"); 

The first line wraps the response in a jQuery object, but then uses html() to return the same HTML that the message was in the first place. Then, you wrap the source again.

You should use:

$(msg).find("#immagine").attr("src"); 

... to get the src

SimpleCoder
still undefined alert! and still working on chrome and firefox
Mauro
A: 

I don't really know why that works in any browser, the context should be an element, a document or a jQuery object, not a string.

Use the jQuery object as context instead of getting the html code from it:

var code = $(msg); 
var title = $("#immagine", code).attr("src"); 
alert( title);
Guffa
same problem! I always got this "undefined" alert
Mauro
@Mauro: Is the HTML code valid? What does it look like? I tried with the value `var msg = '<div><img id="immagine" src="asdf" /></div>';` and it works in IE.
Guffa
There was an error in the HTML code! I've closed a <b> tag with </> This mistaque was invalidating HTML! Thanks a lot dude.
Mauro