Reputation: 5732
Is there a way to check if a CSS selector ( obtained by document.styleSheets[666].rules[1984].selectorText
) matches a specific element ?
I am asking for a cross browser pure javascript solution, but i will consider using jQuery if it is simply done in it.
Upvotes: 1
Views: 365
Reputation: 618
Searching for a particular CSS rule
The below example searches for the "a:hover" rule within the style sheet, and if found, returns a reference to it:
var mysheet=document.styleSheets[0]
var myrules=mysheet.cssRules? mysheet.cssRules: mysheet.rules
for (i=0; i<myrules.length; i++){
if(myrules[i].selectorText.toLowerCase()=="a:hover"){ //find "a:hover" rule
targetrule=myrules[i]
break;
}
}
ref: http://www.javascriptkit.com/dhtmltutors/externalcss3.shtml
Upvotes: 1
Reputation: 22508
For modern browsers, there's matchesSelector
. For less modern browsers, you can use querySelectorAll
and walk the DOM.
Don't use jQuery. Sizzle is enough.
Sizzle.matchesSelector(element, selector)
https://github.com/jquery/sizzle/wiki/Sizzle-Documentation
Upvotes: 3