Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting Element Path for selector

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!

like image 572
owenmelbz Avatar asked Sep 28 '12 16:09

owenmelbz


People also ask

How do I grab an element from a DOM?

The easiest way to access a single element in the DOM is by its unique ID. You can get an element by ID with the getElementById() method of the document object.

What is DOM path?

Definition of Document Object Model (DOM) path for an HTML element: DOM path of an element is the position of the element in the HTML code. For example, in Figure 4 the DOM path of the button (DOM button ) is Document. Html. Body.

How do I find the DOM?

You can search the DOM Tree by string, CSS selector, or XPath selector. Focus your cursor on the Elements panel. Press Control + F or Command + F (Mac). The Search bar opens at the bottom of the DOM Tree.


1 Answers

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')

like image 153
jcern Avatar answered Oct 01 '22 12:10

jcern