capdragon
capdragon

Reputation: 14899

find text string in XML

How would i find the xml node that has a certain text value?

example i want to do something like this which is not working:

var xml = "<data><itemB>more data</itemB><itemC>yes, more data</itemC><itemA>some data</itemA></data>";

var searchString = "more data";

var foundin = $(xml + ":contains(" + searchString + ")");

Upvotes: 3

Views: 3244

Answers (3)

Josh - TechToolbox
Josh - TechToolbox

Reputation: 335

These guys beat me to it, but here is the example I made.

    <script>
        $(function(){
            var xml = "<data><itemB>more data</itemB><itemC>yes, more data</itemC><itemA>some data</itemA></data>";
            var query = "more data";
            $(":contains(" + query + ")", xml).each(function(){
                alert(this.localName); //show node name
            });
        });
    </script>

Edit I'm assuming you're trying to get to the xml node with the query text. You probably want to use nodeName instead of localName for better IE support.

Upvotes: 1

jgeralnik
jgeralnik

Reputation: 126

Try $(xml).children('*:contains("more data")')

Upvotes: 1

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 262939

You can invoke the :contains selector with the root XML element as its context:

var foundin = $(":contains(" + searchString + ")", xml);

You can see the results in this fiddle.

Upvotes: 3

Related Questions