Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query HTML returned from AJAX

Tags:

html

jquery

ajax

How can I query HTML thats returned from AJAX?

I tried

$.post("gethtml.php", { url: $url.val() }, function(data) {
    var $html = $(data),
            $links = $("link, script, style", $html),
            $body = $("body", $html);

    $links.each(function() { $(this).addClass("tmp"); });
    console.log($html);
    console.log($body.html());
});

$html looks like [meta, title, script, style#gstyle, script, textarea#csi, div#mngb, iframe, center, script, script] and $body.html() null

UPDATE

A simple setup at http://jsfiddle.net/uvnrJ/1/

$(function() {
  var html = "<!doctype html><html><head><title>title here ... </title></head><body>This is the body</body></html>",
      $html = $(html);
  console.log($html); // jQuery(title, <TextNode textContent="This is the body">)
  console.log($html.find("body")); // jQuery()
  console.log($html.find("title")); // jQuery()
  console.log($html.filter("title")); // jQuery(title)
});

Shows that jQuery seem to have problems parsing the HTML string?

like image 832
JM at Work Avatar asked Nov 28 '25 15:11

JM at Work


2 Answers

Try this...

..........
var elements = $('<div></div>');
elements.html(data);
alert(elements.find('body').html());
...........
like image 177
Paul Johnson Avatar answered Dec 01 '25 05:12

Paul Johnson


I think you should search for your elements directly in the data variable or use the find() method on $(data). Something like:

$.post("gethtml.php", { url: $url.val() }, function(data) {
    var $html = $(data).find('html'), // First way
        $links = $("link, script, style", data), // Second way
        $body = $("body", data); // Could be better written as $(data).find('body')

    $links.each(function() { $(this).addClass("tmp"); });
    console.log($html);
    console.log($body.html());
});
like image 24
Sylvain Guillopé Avatar answered Dec 01 '25 04:12

Sylvain Guillopé



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!