Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert xPath to jQuery Selector

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(); 
like image 614
user1754738 Avatar asked Mar 21 '14 22:03

user1754738


2 Answers

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:

let xpath = '/html/body/div[4]/div[2]/div/div/div/ul/li[4]';
let jq_sel = xpath
    .substr(1) //discard first slash
    .replace(/\//g, ' > ')
    .replace(/\[(\d+)\]/g, ($0, i) => ':nth-child('+i+')');
like image 80
Mitya Avatar answered Oct 07 '22 20:10

Mitya


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)')
like image 30
razielx4crazy Avatar answered Oct 07 '22 21:10

razielx4crazy