Alex Rivera | Logout

Getting Element Path for selector

Asked 2012-09-28T16:48:21.220
8

Running into a spot of trouble and basically trying to create a variable which can be used as a selector. eg

$('a').click(function(){
   var selector = $(this).dompath();
});

HTML:

html
    body
        div
            div /div
        /div
       ul
         li
         li
       /ul
    div
        ul
           li
           li
           li hello world
        /ul
   /div
   body
html

this would then return something like

path = html body div ul li:contains('hello world')

then i could use this in a selector to select this div so if i did like

$(path).text() would return "hello world"

many thanks!

Edit
Report

2 Answers

16

Perhaps something like this:

function dompath( element )
{
    var path = '';
    for ( ; element && element.nodeType == 1; element = element.parentNode )
    {
        var inner = $(element).children().length == 0 ? $(element).text() : '';
        var eleSelector = element.tagName.toLowerCase() + 
           ((inner.length > 0) ? ':contains(\'' + inner + '\')' : '');
        path = ' ' + eleSelector + path;
    }
    return path;
}

This modified a method from another question to go through, and add in the full text contents of the tag via a :contains() operator only if the tag has no children tags.

I had tested with this method:

$(document).ready(function(){
    $('#p').click(function() {
      console.log(dompath(this));
    });
});

Against this:

<html>
    <body>
        <div>
            <div> </div>
        </div>
       <ul>
         <li></li>
         <li></li>
       </ul>
       <div>
         <ul>
           <li id="p">hi</li>
           <li></li>
           <li id="p2">hello world</li>
        </ul>
       </div>
   <body>
<html>

The results of clicking on p then get output as:

html body div ul li:contains('hi')

answered 2012-10-03T19:53:59.557
0

The request is kind of silly, since there's a much better way.

Either assign a unique ID to the element to quickly reference it later, or if an ID is already assigned use it.

//
// generate a unique (enough) id for an element if necessary
//
function getUID(id) {
    if(window["uidCounter"]==null)
        window["uidCounter"]=0;
    return id||( (window["uidCounter"]++) + "_" + (new Date()).getTime() );
}
//
// use an #ID selector
//
$('a').click(function(){
   var uid = getUID( $(this).attr('id') );
   $(this).attr('id', uid);
   var selector = "#" + uid;
});
answered 2012-10-10T18:25:04.383

Your Answer