Convert xPath to jQuery Selector

巧了我就是萌 提交于 2019-12-24 09:03:03

问题


How do I convert the following xPath into a jQuery 1.10 selector?

/html/body/div[4]/div[2]/div/div/div/ul/li[4]

I'd like to use the result to do something like this:

jQuery('selector').hide(); 

回答1:


Well, it's a question of identifying the syntactical differences:

  • XPath uses / as a parent/child delimiter, while CSS/jQuery selectors use >.
  • XPath uses one-indexed square brackets to denote index, whereas jQuery uses the :nth-child() pseudo-selector

So:

var
xpath = '/html/body/div[4]/div[2]/div/div/div/ul/li[4]',
jq_sel = xpath
    .substr(1) //discard first slash
    .replace(/\//g, ' > ')
    .replace(/\[(\d+)\]/g, function($0, i) { return ':nth-child('+i+')'; });



回答2:


This would be something like this:

$('html body div:eq(4) div:eq(2) div div div ul li:eq(4)')

Im not sure about divs, maybe it could be like this another one:

$('html body div:eq(4) div:eq(2) div:first div:first div:first ul li:eq(4)')


来源:https://stackoverflow.com/questions/22570904/convert-xpath-to-jquery-selector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!