views:

74

answers:

1

hi,

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  A: 

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); });
Nick Craver