Answer the question
In order to leave comments, you need to log in
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>
body div#container div#comments ul:nth-child(0) li:nth-child(0)
#comments li:nth-child(0)
Answer the question
In order to leave comments, you need to log in
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(' '));
});
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 questionAsk a Question
731 491 924 answers to any question