6

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?

Community
  • 1
  • 1
fsinisi90
  • 1,138
  • 1
  • 16
  • 45
  • Why not just store a reference to that element in a variable within scope of all the required functions? – Rory McCrossan Apr 06 '16 at 13:20
  • `getPathTo(jQuery('h3').first()[0])` – epascarello Apr 06 '16 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 Apr 06 '16 at 13:27
  • @RoryMcCrossan because I need the element to be retrieved in another session. – fsinisi90 Apr 06 '16 at 13:27
  • @epascarello Thanks, it works. Maybe you want to post it like an answer. – fsinisi90 Apr 06 '16 at 13:27
  • @FranCavs90 then why not just call `$('h3:first')` in that session? – Rory McCrossan Apr 06 '16 at 13:36
  • @RoryMcCrossan That was just an example. I need to save multiple DOM elements so I can replace them with others lather (and this replacement depends of other unrelated events). – fsinisi90 Apr 06 '16 at 13:56
  • Ok fair enough. Though my point remains; I'm sure there's a better way to do this than using XPath. – Rory McCrossan Apr 06 '16 at 13:58
  • @RoryMcCrossan Yes, there is. I'm working on an algorithm that will try to find the element in multiple ways, XPath is just one of them. Another point is that I have no control over the DOM elements - maybe they can change over the time. – fsinisi90 Apr 06 '16 at 14:02

1 Answers1

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))
epascarello
  • 204,599
  • 20
  • 195
  • 236