6
votes

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?

1
Why not just store a reference to that element in a variable within scope of all the required functions?Rory McCrossan
getPathTo(jQuery('h3').first()[0])epascarello
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
@RoryMcCrossan because I need the element to be retrieved in another session.fsinisi90
@epascarello Thanks, it works. Maybe you want to post it like an answer.fsinisi90

1 Answers

5
votes

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