How to get all DEFINED CSS Selectors for a given DOM Element using jQuery?
With defined I mean all CSS Selectors which are used in any of the Stylesheets applied to the
From this answer you might be able to get what you are looking for by looping through the cssRules property.
var myElement = $("#content");
for (var x = 0; x < document.styleSheets.length; x++) {
var rules = document.styleSheets[x].cssRules;
for (var i = 0; i < rules.length; i++) {
if (myElement.is(rules[i].selectorText)) {
$("ul").append("- " + rules[i].selectorText + "
");
}
}
}
Given the following dom:
And css rules:
div
{
background-color:black;
}
#content{
height:50px;
width:50px;
}
div > div
{
border: solid 1px red;
}
We would get a matched rule set of:
body, div, dl, dt, dd, ul, ol, li, h1, h2, h3, h4, h5, h6, pre, form,fieldset, input, textarea, p,
blockquote, th, td div
#content
div > div
Example on jsfiddle. Not sure how well this will work for all scenarios but might be something to look at if it will fit your needs.
Updated with a slightly more complete example...
$(document).click(function(event) {
var rules = GetAppliedCssRules($(event.target));
var $ul = $("#rules").empty();
$.each(rules, function() {
$ul.append("- " + this + "
");
});
event.preventDefault();
});
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;
}