0

How to select items whose sub-tag key's text starts with '001'?

<root>
    <item>
        <key>001001</key>
        <text>thanks</text>
    </item>
    <item>
        <key>001002</key>
        <text>very</text>
    </item>
    <item>
        <key>002001</key>
        <text>much</text>
    </item>
</root>



$(xml).find("item>[filter string]").each(function()
{
    alert(this);
});
1
  • Do you control the XML schema? Promoting the children to attributes might work better (<item key="001001" text="thanks">). Even just the key if there exists a lot more under an <item>. Commented Apr 20, 2010 at 2:38

1 Answer 1

1

You need .filter() in this case:

$(xml).find("item").filter(function() {
  return $(this).find("key").text().indexOf('001') === 0;
}).each(function() {
    alert(this);
});

This filters the items by those having a key element who's text starts with 001. If you could modify the schema at all though, this would be much faster...searching in the children for the filter is a bit expensive overall if you're dealing with many items.

Jake's comment suggestion is a good one if it's an option, if an item had attributes instead of inner elements, you could do it much simpler with the attribute starts-with selector, like this:

$(xml).find("item[key^=001]").each(function() { alert(this); });
Sign up to request clarification or add additional context in comments.

Comments

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.