1
1
1nd1go2011-08-12 11:41:12
css
1nd1go, 2011-08-12 11:41:12

Forming a CSS selector for a specific DOM element

Greetings,

Has anyone seen a JS script, a jquery plugin, or just someone who can suggest an algorithm for getting a CSS selector for a specific element of the DOM tree of the page.

For example there is this:

<body>
  <div id="container">
    <ul id="menu"> ... </ul>
    <div id="comments">
      <ul>
        <li>Первый нах</li>
      </ul>
    </div>
  </div>
</body>


And now I want to get a CSS selector for the “First fuck” comment.

In the simplest case, you can have:
body div#container div#comments ul:nth-child(0) li:nth-child(0)


At best, something more optimized:
#comments li:nth-child(0)


Thank you!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Y
yopopt, 2011-08-12
@yopopt

Your version is not far from the truth, but I would do something like this:


$(document).one('click', function(event) {
  var q = function (i, e) {
    if(e.tagName.toLowerCase() !== 'body') {
      if((!$(arr[0]).attr('id') && e.id) || $(e).length > 1 || i == -1)
        arr.push( 
          (e.id && "#"+e.id)
          || (e.className && e.tagName.toLowerCase()+"."+e.className) 
          || (e.tagName.toLowerCase() + ":eq(" + $(e).index() + ")")
        );
      if(e.id)
        return false;
    }
    else
      return false;
  }
  var arr = [];
  q(-1,event.target);
  $(event.target).parents().each(q);
  console.log(arr.reverse().join(' '));
});

Produces the most optimized result.

1
1nd1go, 2011-08-12
@1nd1go

So far I've written something like:

$(document).one('click', function(event) {
  var i=100, arr = [], current = $(event.target);
  
  while(i-- > 0  && current[0].nodeName.toLowerCase() !== 'body') {
    arr.push( 
      (current.attr('id') && "#"+current.attr('id')) 
      || (current.attr('class') && current[0].nodeName.toLowerCase() +"."+current.attr('class')) 
      || (current[0].nodeName.toLowerCase() + ":eq(" + current.index() + ")"));
    current = current.parent();    
  }

  console.log(arr.reverse().join(' '));
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question