admin管理员组

文章数量:1334342

I need to get the XPath of a DOM element to persist it so I can look for that element lather.

I've tried the getPathTo method of this answer but when I call the method with a jQuery-created object like this...

getPathTo(jQuery('h3').first());

...I get this error:

Uncaught TypeError: Cannot read property 'childNodes' of undefined(…)

I've tried to replace parentNode with parent(), childNodes with children(), and tagName with prop('tagName'), but then I received undefined as the function result...

So, do you have a similar function to getPathTo that works with jQuery?

I need to get the XPath of a DOM element to persist it so I can look for that element lather.

I've tried the getPathTo method of this answer but when I call the method with a jQuery-created object like this...

getPathTo(jQuery('h3').first());

...I get this error:

Uncaught TypeError: Cannot read property 'childNodes' of undefined(…)

I've tried to replace parentNode with parent(), childNodes with children(), and tagName with prop('tagName'), but then I received undefined as the function result...

So, do you have a similar function to getPathTo that works with jQuery?

Share Improve this question edited May 23, 2017 at 12:17 CommunityBot 11 silver badge asked Apr 6, 2016 at 13:18 fsinisi90fsinisi90 1,1581 gold badge17 silver badges49 bronze badges 9
  • Why not just store a reference to that element in a variable within scope of all the required functions? – Rory McCrossan Commented Apr 6, 2016 at 13:20
  • getPathTo(jQuery('h3').first()[0]) – epascarello Commented Apr 6, 2016 at 13:21
  • I Think your Problem is that you use a documentElement in jQuery Context. You can try to extract the element to javascript native level. Like this: var element = jQuery('h3'); element.childNodes.... – Denis Kohl Commented Apr 6, 2016 at 13:27
  • @RoryMcCrossan because I need the element to be retrieved in another session. – fsinisi90 Commented Apr 6, 2016 at 13:27
  • @epascarello Thanks, it works. Maybe you want to post it like an answer. – fsinisi90 Commented Apr 6, 2016 at 13:27
 |  Show 4 more ments

1 Answer 1

Reset to default 5

The method expects a DOM node and you are giving it a jQuery object

getPathTo(jQuery('h3').first()[0])

or

getPathTo(jQuery('h3').first().get(0))

本文标签: javascriptGet XPath of a DOM element with jQueryStack Overflow