2

I have an element such as element = document.getElementyById("myElement");

Now, let us assume that there is some CSS applied on it through various methods such as #id, .class, and tagName.

We know that #id has priority over .class and .class has priority over tagName. I want to determine which of the above method is applied on that element i.e. I want to see if is has CSS applied on it using id, class, or tag. How would I find that out? Is there any JavaScript Library available for that?

U.P
  • 7,357
  • 7
  • 39
  • 61
  • 2
    An element may have CSS applied using any of these methods or a mixture thereof; most often it has several styles, each style using a mixture of rules. As such this is a really complex problem, and for its complexity it's not very well defined. As the question stands, the answer for most elements on an average website will be "all three". May I ask what you want to use this for? – deceze Nov 09 '10 at 08:36
  • 2
    there will also be inherited css rules by ancestors.. you should use firebug which shows all cases and in detail.. – Gabriele Petrioli Nov 09 '10 at 08:40
  • Actually, I am developing something similar to Firebug and I require the CSS selector. Once I know it, I'll be able to change CSS and use that selector to render that element in the browser. – U.P Nov 09 '10 at 11:25

2 Answers2

2

Go through the document.styleSheets object, iterate over each styleSheet object, then each rule. You will then have to parse the selectorText property, essentially writing your own CSS parser while maintaining an internal array on the specificity of each selector.

Compare the specificity of the current rule with the previous ones, then determine which property override which. After all that, you'll still need to check for inheritance - go through each of the parent of the element in question and look for properties that can be inherited, and add them to this list if they're not already set on the children. This also means that you'll need to maintain a set of properties that inherits.

If you haven't realised, this is quite an undertaking. Why not just go and use whatever developer tools that are available for your browser and look at the CSS rules provided by those instead.

Yi Jiang
  • 49,435
  • 16
  • 136
  • 136
  • how about window.getcomputedstyle(element)? – U.P Nov 09 '10 at 11:26
  • @UmairP https://developer.mozilla.org/en/DOM:window.getComputedStyle - "`getComputedStyle()` gives the [final used](https://developer.mozilla.org/en/CSS/used_value) values of all the CSS properties of an element." – Yi Jiang Nov 09 '10 at 14:13
0

Why dont you check

element = document.getElementyById("myElement");
if (element.tagName != "") { ... }
if (element.id != "") { ... }
if (element.className != "") { ... }
Simon
  • 4,395
  • 8
  • 33
  • 50