Search code examples
javascriptjqueryxhtmliterationnodes

How to iterate through own made xhtml nodes with javascript or jquery


I have an ajax handler that gets pieces of pages in parts like:

<load loadloc="list" method="append" animation="fadein" >
      <li>add something to a list</li>
</load>
<load loadloc="thediv">
      <h1>hello there</h1>
      <p>this is a paragraph</p>
</load>
<load loadloc="theotherdiv">
      <img src="url.com" />
</load>

It iterates over the load elements with $(htmlfromajax).filter(function(){ do stuf here });

It works great but when php puts in an error, or I myself put in some other html it tries to iterate over every single line or it just doesn't work. (in js I can't write on multiple lines but when receiving the ajax I get multiple lines so)

some php error here
<load loadloc="list" method="append" animation="fadein" >
      <li>add something to a list</li>
</load>
<load loadloc="thediv">
      <h1>hello there</h1>
      <p>this is a paragraph</p>
</load>
<load loadloc="theotherdiv">
      <img src="url.com" />
</load>

A simple example of my ajax handler

How can I use jquery or ajax to only iterate over the load elements?


Solution

  • If you want to keep your response like it is, try using

    ...
    $('<div/>').html(data).find('load').each(function(i, el) {
        // get the load location
        var location = $(el).attr("loadloc");
    ...
    

    instead of

    ...
    $(data).filter(function(){
    ...
    

    See the updated fiddle: http://jsfiddle.net/XC5Kc/2/