0

I want to retrieve the DOM path of a random element in a website (like Firebug or this Greasemonkey userscript ) when I click on this element. No problem for this part, I return a string containing the path.

The only drawback being I don't need a full path such as

html > body > div #mainPanel > table #pageBody > tbody > tr > td 

Just this : #pageBody > tbody > tr > td would be enough to retrieve the element using jQuery or Dojo.

I thought of using a Regexp to remove all that's before the last id, this should not be an issue.

As for class, I'm not sure I can do the same, because it could be useful to see if other elements match the pattern. For example, in my site .DiscreetList > li matches 6 nodes. How can I retrieve the good one?

Are there other possibilities for shortening besides the class and id trick? (for use in jQuery/Dojo or equivalent)

Edit : After the remarks, I found this snippet (© Greg's code)

Now, the problem with index is fixed, and I decided, based on the comments, to shorten by the id, safe way to go :)

Thanks for your answers.

Community
  • 1
  • 1
Michael Lumbroso
  • 4,931
  • 5
  • 27
  • 34

2 Answers2

1

The only elements that you can guarantee to be unique are the ones with id, and you may be able to reason about certain other elements as well (there can be no nested form tags, there is only one head, a tr tag always has an outer table tag, ...) but that's somewhat convoluted. I would stick with id's.

Adam Bergmark
  • 7,316
  • 3
  • 20
  • 23
  • 2
    Then again, you can't guarantee that a web page has a unique id either. It's not valid HTML, but there's nothing stopping it from occurring. – Adam Bergmark May 24 '11 at 15:42
1

In order to accurately locate the element, you would need to also store the index of the element (within it's parent). Otherwise, as Pointy mentioned, even #pageBody > tbody > tr > td would match all td's inside of the tr.

mbxtr
  • 2,323
  • 1
  • 15
  • 12
  • Thanks for your answer. Is there some piece of JavaScript/jQuery that would allow me to retrieve easily nth-child index ? – Michael Lumbroso May 25 '11 at 12:02
  • Found a way to retrieve the index of the element (i edited the original post). Now let's suppose the page is not well-formed, and an id is used several times, will jQuery/Dojo/CSS3 understands something like `#mainShadowed2:eq(2)` – Michael Lumbroso May 25 '11 at 14:34
  • jQuery will only return the first element with a given ID, so the :eq(2) selector will not work. I think the only way to be 100% certain that you could locate a specific node in a document that might be malformed would be to rely only on tags and indices, instead of selectors. – mbxtr May 27 '11 at 14:20