woolagaroo
woolagaroo

Reputation: 1522

Select element with a child element by value with jQuery

If i have the following XML:

<Books>
    <Book>
        <Name>Test</Name>
        ...
    </Book>
    <Book>
        <Name>Another one</Name>
        ...
    </Book>
</Books>

How can I select the Book element with the child element whose name value equals "test" with jQuery?

Upvotes: 3

Views: 4045

Answers (4)

Mark Meuer
Mark Meuer

Reputation: 7523

To avoid selecting Name element, use the .has() filter function like so:

$('Books Book').has('Name:contains("Test")')

This will return the Book items with the name of "Test".

Upvotes: 0

Samir Adel
Samir Adel

Reputation: 2499

$("Books Book Name:Contains('Test')");

Upvotes: 4

Blazemonger
Blazemonger

Reputation: 92893

$('Books Book Name:contains("Test")')

http://api.jquery.com/contains-selector/

(This will match "Test" as well as "Math Test", and "This Is Only A Test".)

Upvotes: 4

Šime Vidas
Šime Vidas

Reputation: 185883

var book = $xml.find( 'Name' ).filter(function () {
    return $( this ).text() === 'Test';
}).parent();

where $xml is the jQuery object that represents the XML document. I assume that you load the XML document via Ajax. In that case you can construct such a jQuery object like so:

var $xml = $( data );

where data is the Ajax-response.

Upvotes: 9

Related Questions