Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to calculate the XPath position of an element using Javascript?
    primarykey
    data
    text
    <p>Let's say I have a large HTML file with different kinds of tags, similar to the StackOverflow one you're looking at right now.</p> <p>Now let's say you click an element on the page, what would the Javascript function look like that calculates the most basic XPath that refers to that specific element?</p> <p>I know there are an infinite ways of refering to that element in XPath, but I'm looking for something that just looks at the DOM tree, with no regard for IDs, classes, etc.</p> <p>Example:</p> <pre><code>&lt;html&gt; &lt;head&gt;&lt;title&gt;Fruit&lt;/title&gt;&lt;/head&gt; &lt;body&gt; &lt;ol&gt; &lt;li&gt;Bananas&lt;/li&gt; &lt;li&gt;Apples&lt;/li&gt; &lt;li&gt;Strawberries&lt;/li&gt; &lt;/ol&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Let's say you click on <em>Apples</em>. The Javascript function would return the following:</p> <pre><code>/html/body/ol/li[2] </code></pre> <p>It would basically just work its way upward the DOM tree all the way to the HTML element.</p> <p>Just to clarify, the 'on-click' event-handler isn't the problem. I can make that work. I'm just not sure how to calculate the element's position within the DOM tree and represent it as an XPath.</p> <p>PS Any answer with or without the use of the JQuery library is appreciated.</p> <p>PPS I completely new to XPath, so I might even have made a mistake in the above example, but you'll get the idea.</p> <p>Edit at August 11, 2010: Looks like somebody else asked a similar question: <a href="https://stackoverflow.com/questions/2537224/generate-get-the-xpath-for-a-selected-textnode/3458558#3458558">generate/get the Xpath for a selected textnode</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload