5

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?

0

3 Answers 3

14

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() )
})
Sign up to request clarification or add additional context in comments.

7 Comments

That's EXACTLY what it was! Thanks!
Bah, scott. See my edit for a workaround so you don't go removing all newlines from your html :)
I was going use filter or trim, but thanks for posting that code.
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: you are right. I meant .html does not operate on non-Element nodes.
|
0

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>

4 Comments

jQuery does not need a single root element when parsing html. For example alert($('<div></div><div></div>').length) results in "2".
But I think .each requires it and that's what I think he meant :)
Neither of those examples work. Do I need to return the data back as a string?
thanks a lot had trouble using "find" to work but you set me on the right track
0

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

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

I haven't tested it though...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.