Convert xPath to jQuery Selector

2019-08-12 07:57发布

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(); 

2条回答
孤傲高冷的网名
2楼-- · 2019-08-12 08:33

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+')'; });
查看更多
萌系小妹纸
3楼-- · 2019-08-12 08:36

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)')
查看更多
登录 后发表回答