scott
scott

Reputation:

Parsing HTML String with Ajax/jQuery

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?

Upvotes: 5

Views: 23953

Answers (3)

sharat87
sharat87

Reputation: 7536

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

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

I haven't tested it though...

Upvotes: 0

Roatin Marth
Roatin Marth

Reputation: 24115

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() )
})

Upvotes: 14

Darko
Darko

Reputation: 38910

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>

Upvotes: 0

Related Questions