Parsing HTML String with Ajax/jQuery

ajax, html, jquery

Solution

I think newlines in `moo.html` may be tripping you up.

Any newlines in your html will end up being parsed by jQuery and kept as text node elements `"\n"`. As a result `$(code).each` will stop iterating when the first of these nodes is hit and you call `.html()` on it (`html()` does not operate on non-Element node types).

What you need is to grab only the `div`s in your html:

var divs = $(code).filter(function(){ return $(this).is('div') });
divs.each(function() {
    alert( $(this).html() )
})

Problem

I asked at Parsing HTML String with jQuery how I can use jQuery on an html string. That all works, but when I apply it to ajax - it does not work. Here is the code. ``` <script> var url = 'moo.html'; $.ajax({ url: url, success: function ( code ) { html = $(code); html.each(function() { alert( $(this).html() ); }); } }); </script> ``` moo.html contains ``` <div id='test'>zebra</div> <div id='foo'>bar</div> ``` How can I get zebra and bar?

Original source

Related problems