A
A
aymeshkov2011-05-25 21:50:27
css
aymeshkov, 2011-05-25 21:50:27

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

5 answer(s)
M
Melanitsky, 2011-05-25
@Melanitsky

$(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;
}

C
chikuyonok, 2011-05-25
@chikuyonok

Wouldn't an XPath selector work? Typebody[1]/div[2]/p[5]

M
Mark, 2011-05-26
@printf

If the element has an id, then it '#' + idis 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.

K
Kirill Dlussky, 2011-06-20
@Dlussky

The simplest, but not the fastest algorithm, in my opinion.
If there is an id, everything is obvious.

U
Ulyan Chesnokov, 2018-11-26
@ulyanchesnokov

Open the inspector in Crome, through cmd + alt + cselect 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 question

Ask a Question

731 491 924 answers to any question