5

Is there a way to take a DOM object and infer a CSS selector that could be used to find that element at a later time.

Example:

<ul class="items">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
</ul>

<script type="text/javascript">
var second = $('.items li:eq(1)');
console.log(get_css_selector(second));
</script>

Where the get_css_selector would return something similar to .items li:eq(1) or at least a string that would work to select the element.

Bonus would be if there was a method to generate a CSS selector based on:

<script type="text/javascript">
var third = document.getElementsByTagName('li')[2];
console.log(get_css_selector(third));
</script>
dlrust
  • 2,433
  • 19
  • 20
  • 2
    possible duplicate of [Get CSS path from Dom element](http://stackoverflow.com/questions/3620116/get-css-path-from-dom-element). +1 for a well written question, though. – Andy E Sep 03 '10 at 23:52

2 Answers2

3

It appears as though you're trying to use the original selector. Am I right about that? Or have I over-simplified things?

The original selector is stored in the jQuery object you created.

Try it: http://jsfiddle.net/9JUJL/

var second = $('.items li:eq(1)');
var selector = second.selector;

Or for the bonus, this? http://jsfiddle.net/9JUJL/2/

function get_css_selector(elem) {
    var tag = elem.tagName.toLowerCase();
    return tag + ':eq(' + $(tag).index(elem) + ')';
}
user113716
  • 318,772
  • 63
  • 451
  • 440
1
function createElementSelector(elm, containedInEle) {
    containedInEle = typeof(containedInEle) != 'undefined' ? containedInEle : document;

    var segs = [];

    for (; elm && elm !== containedInEle; elm = elm.parentNode) 
    { 
        segs.unshift(':nth-child(' + childNumber(elm) + ')'); 
    }; 
    return '#' + elm.id + ' ' + segs.join(' '); 
}; 

function childNumber(child) { 
    var i = 0;
    while( child.nodeType == 1 && (child = child.previousSibling) != null) {
      i++;
    }
    return i + 1; 
}; 
Fuji
  • 28,214
  • 2
  • 27
  • 29