tags:

views:

59

answers:

3

I know that Attr gets the exact class of an element. Is there a way to get the element exact class as defined in CSS? For example an element may have class "title" but be defined in CSS as a descendant selector, something like: .other-list .title {} I need something to get that exact class value. You can see here the full example: http://jsfiddle.net/2TMgQ/2/

On click both elements have class "title" but are defined in CSS as 2 different elements. Thank you

A: 

If you are referring to parent - child selectors then the syntax would be something like:

$(".other-list > .title")

Have a look at http://api.jquery.com/category/selectors/

gnome
He wants to GET the parent class
Marko
+1  A: 

This should get you all CSS styles that apply to the element. It uses jQuery's is function to check if a CSS rule selector applies to a given element. Iterate through all stylesheets in document.styleSheets, and through all cssRules in each stylesheet, and check if selectorText matches the element. In pseudocode:

given::element

matchedRules = []

for styleSheet in document.styleSheets
    for rule in styleSheet.cssRules
        if element.is(rule.selectorText)
            matchedRules.push(rule.selectorText)

return matchedRules;

In code:

function getCSSRules(element) {
    element = $(element);

    var styleSheets = document.styleSheets;
    var matchedRules = [], rules, rule;

    for(var i = 0; i < styleSheets.length; i++) {
        rules = styleSheets[i].cssRules;

        for(var j = 0; j < rules.length; j++) {
            rule = rules[j];
            if(element.is(rule.selectorText)) {
               matchedRules.push(rule.selectorText);
            }
        }
    }

    return matchedRules;
}

This should return all rules that apply to the element. For your first example, it returns:

[".links-list .title"]

For Nick's extended example, it returns:

[".links-list .title", ".title", "a", "li a"]

How you define specificity and how to decide what to filter out from this list is upto you.

Anurag
This is the exact result I need. Let me try it out.
Mircea
Thanx, this is getting the exact selectors as Firebug.
Mircea
You're welcome. Glad it worked for you!
Anurag