[removed] use xpath in jQuery

前端 未结 8 1362
耶瑟儿~
耶瑟儿~ 2020-12-14 10:16

I have, for example, the next XPath query:

//div[span=\"something\"]/parent::div/child::div[@class=\\\"someClass\\\"]

I want to use this XP

8条回答
  •  太阳男子
    2020-12-14 10:30

    You can re-write your xpath queries as CSS selectors:

    $('div:has(> div > span:contains(something)) > div.someClass');
    

    You can achieve the same effect as parent:: using the :has pseduo selector to select an element based on its children: div.foo:has(> div.bar) will select all div elements with class foo that have a child div with class bar. This is equivalent to div[@class="bar"]/parent::div[@class="foo"].

    See:

    • jQuery API: Selectors
    • Sizzle documentation

    You could probably approach this in several other ways using various combinations jQuery's DOM traversal methods. For example, this would be a very direct translation of your xpath query:

    $('div:has(> span:contains(something))')  // //div[span="something"]
        .parent('div')                        // /parent::div
        .children('div.someClass');           // /child::div[@class="someClass"]
    

    It's worth noting that div.someClass in CSS isn't the exact equivalent of div[@class="someClass"] in xpath. The CSS will match

    , but the xpath won't. See Brian Suda's article on parsing microformats with XSLT for more detail.

提交回复
热议问题