uriDium
uriDium

Reputation: 13420

How can I use JQuery to get all nodes with an attributes equal to a value?

I am getting some XML back from an AJAX call (no surprise) and I want to do something but only on certain nodes and something else on the rest. For example

<xml>
  <node name="x">
  </node>
  <node name="x">
  </node>
  <node name="y">
  </node>
  <node name="z">
  </node>
</xml>

I want all the nodes with name x to go to one table and I want all the others to go to another table.

Upvotes: 10

Views: 28293

Answers (4)

Martijn Pieters
Martijn Pieters

Reputation: 1121366

Use an attribute filter, in particular the attributeEquals filter:

$("node[name='x']");

To select all the other nodes, use the attributeNotEquals filter:

$("node[name!='x']");

You can then apply jQuery manipulations to move these nodes elsewhere.

Note that XPath-style selectors where deprecated in version 1.2, and have been removed altogether in jQuery 1.3.

If you can influence what the server sends, you may want to switch to using JSON instead, you may find it easier to parse.

Upvotes: 21

Daniel Moura
Daniel Moura

Reputation: 7966

success: function(xml) {
   $(xml.find('node').each(function(){
    if($(this).attr('name')=='x') {
       //go to one table
    } else {
       //go to another table
    }

   }
}

Upvotes: 8

Scott Baker
Scott Baker

Reputation: 10443

jQuery accepts xpath expressions as well.

$('node[name="x"]')

will select all the nodes named "node" with an attribute of "name" that has the value "x"

Upvotes: 2

You can use xpath in jQuery to select the nodes:

$("//node[@name='x']")

http://docs.jquery.com/DOM/Traversing/Selectors

Upvotes: 2

Related Questions