开发者

JavaScript for Searching an Element's Specific Ancestor Like in XPath?

Searching downwards from a given node works wonderfully and crossbrowser-compatible with Javascript functions querySelectorAll() and querySelector().

This functions allow to state any CSS3 selector for searching child elements. As far as I have understood, there is no way to search parental nodes: W3 CSS3 Selectors

I'd like to search parent nodes too like possible with XPath axe ancestor. Something like (XPath):

select="./ancestor::*[@attributex='xxx'][2]"

Note 开发者_运维百科that I haven't tried out the above XPath expression, and I'm not sure if it only selects the nearest ancestor, but that was my intention.

I know that I could directly use XPath in JavaScript, but I'd rather avoid it as I don't know about 1) browser compatibility and 2) searching downwards works fine with querySelector/All().

I'd also rather avoid some for-loop searching one .parentNode after the other and compare its .getAttribute("attributex") with the searched one.

Any ideas how to accomplish this with cross-browser-compatible JavaScript?


I think you would appreciate jQuery's parents([selector]) method. For sure it take advantages in terms of compatibility. Take a look at http://api.jquery.com/parents/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜