n00b
n00b

Reputation: 5732

javascript - Check if CSSRule matches Element

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

Answers (3)

Alvin Pradeep
Alvin Pradeep

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

Prinzhorn
Prinzhorn

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

Eric
Eric

Reputation: 97631

It's really simple in jQuery:

$(element).is(cssSelector);

Upvotes: -2

Related Questions