tags:

views:

1295

answers:

3

I asked at http://stackoverflow.com/questions/1529333/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?

+1  A: 

try $('div', code).each instead.. like so...

$('div', code).each( function () {
  alert($(this).text());
});

I haven't tested it though...

Shrikant Sharat
A: 

Try:

html = $("div", code);
html.each(function() {
    alert($(this).html());
});

The reason you can't do it the way you have it, is because when parsing HTML jQuery wants to have a single root element. If it doesn't then you have to do it the way above. The following HTML/JS would also work:

var html = $(code);
html.children().each(....);

<div>
    <div id='test'>zebra</div>
    <div id='foo'>bar</div>
</div>
Darko Z
jQuery does not need a single root element when parsing html. For example `alert($('<div></div><div></div>').length)` results in "2".
Roatin Marth
But I think .each requires it and that's what I think he meant :)
Shrikant Sharat
Neither of those examples work. Do I need to return the data back as a string?
scott
+1  A: 

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 divs in your html:

var divs = $(code).filter(function(){ return $(this).is('div') });
divs.each(function() {
    alert( $(this).html() )
})
Roatin Marth
That's EXACTLY what it was! Thanks!
scott
Bah, scott. See my edit for a workaround so you don't go removing all newlines from your html :)
Roatin Marth
I was going use filter or trim, but thanks for posting that code.
scott
uh jQuery works fine on non-Element node types. You need to check each item's nodeType. 1 are html elements, 3 would be textNodes
Scott Evernden
@Scott: you are right. I meant `.html` does not operate on non-Element nodes.
Roatin Marth
'var divs = $(code).filter(function(){ return $(this).is('div') });' is the goofy way of saying '$('div', code)' .. double check sharat87's answer - he had it right?
Scott Evernden
@Scott: `$('div', code)` traverses *down* into each element in the jQuery set defined by `code`, looking for *child* divs. OP needs the divs themselves, not child divs therein. Hope that clears it up a bit.
Roatin Marth