6

If you have the xml below in $(xml), you would get droopy using:

$(xml).find("animal").find("dog").find("beagle").text()

Is there an equivalent way in jQuery to use xpath like

$(xml).xpathfind("/animal/dog/beagle").text()?

<animal>
    <dog>
        <beagle>
            droopy
        </beagle>
        ...

2 Answers 2

6

jQuery supports basic XPath actually, so you can just use find.

Alternatively, use CSS selector syntax. For your particular example, you would use $(xml).find( "animal > dog > beagle" ).text()

Sign up to request clarification or add additional context in comments.

1 Comment

And for getting attribute value you could use $(xml).find("element").attr("attribute")
5

jQuery used to support very basic XPath, including the example you gave.

$(xml).find("animal/dog/beagle")

EDIT: You're right, they've apparently removed it from the core, so you have to use a "compatibility" plugin.

EDIT: Updated link to xpath plugin XPath Plugin

3 Comments

I tried it, but it didn't work. The CSS selector syntax, "animal > dog > beagle" did. I tried "/a/d/b", "//a/d/b" too. Do I have to include a plugin?
I think it has to do with the leading slash. Try "a/d/b" instead of "/a/d/b"
Yeah, I tried an old xpath plugin from Resig, but looking at the source, it was minimal coverage of xpath. Oh well, the CSS selector will do. Just wanted to make sure there if xpath was part of the latest jQuery.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.