16

I am trying to get the path in the html dom for a specific object.
Using javascript or jquery.(When I select/hover over the object.)

I do not know the structure in advance.

For example:

<html>
    <body>
        <div>
            <div>
                Not selected
            </div>
            <div>
                Selected Text
            </div>
        </div>
    </body>
</html>

The "Selected Text" Div path should be something like:

//HTML/BODY/DIV[0]/DIV[1]

Any help will be appreciated.

I have looked at this answer but it does not give an indication regarding the index of the element (In my example the value in the square brackets - 1 in DIV[1]).

By the way is there a "technical" name for this path?
I have seen the term XPath but am not sure that this is it.

Be happy and enjoy life.

Community
  • 1
  • 1

2 Answers2

17

The following function does what you want, using jQuery:

function getElementPath(element)
{
    return "//" + $(element).parents().andSelf().map(function() {
        var $this = $(this);
        var tagName = this.nodeName;
        if ($this.siblings(tagName).length > 0) {
            tagName += "[" + $this.prevAll(tagName).length + "]";
        }
        return tagName;
    }).get().join("/").toUpperCase();
}

You can use it like this:

$(document).ready(function() {
    $("div").click(function(event) {
        event.stopPropagation();
        window.alert(getElementPath(this));
    });
});

You can test it here.

Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
1

$("html > div")[0].find("div")[1]

XPath is not available in Jquery anymore.

If you need Xpath, just use Firebug under FF, or Chrome.

Concerning having anyelemtn being selected(option) :

$("option:selected")

To get a div being hover :

$("div:hover")

or a checkbox :

$("checkbox:selected")

Now let's take an example:

<div>
   <div class='again'>
      <select id='select1'>
         <option val='1'>
         <option val='2'>
      </select>


      <select id='select2'>
         <option val='1'>
         <option val='2'>
      </select>
   </div>
</div>

Now how to get the first list being selected :

$("#select2 > option:selected")

or

$('.again >select')[0].find("option:selected")

getting the div being hovered :

('.secondDIv').hover(function(){
},function(){});

etc etc

Ant
  • 1,812
  • 5
  • 22
  • 39
  • @user544287 I am not sure that you understood my question. I am trying to get the path of any element that is selected/hovered not only the example that I gave. –  Dec 16 '10 at 10:05