开发者

How to select children but not the root element (with same name) in jQuery

in my XML I have some child elements with the same name as the root element. I am looking for a way to select just those child elements, but not the root element. I've been looking through the jQuery selector documentation, and googled a bunch, but the only thing I can find is people who are facing the opposite problem: selecting children AND root, which is what is working perfectly fine (too fine :) ) for me!

Here is some example XML:

<myElement>
    <someElementWithVariableName>
        <someMoreVariationElement>
            <myElement>
                <leafNode1/>
                <leafNode2/>
            </myElement>
  开发者_如何学Go          <myElement/>
        </someMoreVariationElement>
    <someElementWithVariableName>
</myElement>

Now when I do the following I will get 2 objects: the root element and the 2 child elements of someMoreVariationElement:

$(inputXml).find("myElement")

I was wondering, maybe I can use

$(inputXml).find("myElement > *")

But that only works just in the cases where myElement is actualy the root element, but that is not guaranteed. It can be something else. Just like someElementWithVariableName and someMoreVariationElement, which can both be anything. So basically... I need a selector that will only get myElement if it is a child of something.

(It would be even better if it only selects all instances of myElement at level 3 (counting root as level 0, someElementWithVariableName as level 1, and someMoreVariationElement as level 2))


In this particular case, you should be able to use the following code. (Example using Divs)

$(inputXml).find("myElement:not(:first)")


Actually if myElement is the root element then it will not get included in the result set, as the find look under the selected node.

Quoting from the documentation of .find() docs

Description: Get the descendants of each element in the current set of matched elements, filtered by a selector.

What you need is $(inputXml).find("* > myElement")

But if the myElement is indeed nested (at any depth) under another myElement you will get both of those (assuming the parent is not the root as well..)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜