Answer the question
In order to leave comments, you need to log in
Javascript: Get CSS selectors by element
An unusual task of this kind arose:
We need to get all the CSS selectors that uniquely identify a given element on the page.
Does anyone know of an existing solution?
If not, can you suggest a simple solution algorithm?
Answer the question
In order to leave comments, you need to log in
$(document).click(function(event) {
console.log(GetAppliedCssRules($(event.target)));
});
function GetAppliedCssRules($element) {
var appliedRules = [];
for (var x = 0; x < document.styleSheets.length; x++) {
var rules = document.styleSheets[x].cssRules;
for (var i = 0; i < rules.length; i++) {
if ($element.is(rules[i].selectorText)) {
appliedRules.push(rules[i].selectorText);
}
}
}
return appliedRules;
}
If the element has an id, then it '#' + id
is a selector that uniquely identifies this element on the page.
If the element does not have an id, a unique id must be generated; GOTO 10 You can't
get all the CSS selectors that point to this element - there are an infinite number of them.
The simplest, but not the fastest algorithm, in my opinion.
If there is an id, everything is obvious.
Open the inspector in Crome, through cmd + alt + c
select the desired element, which will be highlighted in the Elements panel and from there through the menu Copy - Copy selector to get the exact selector.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question