Is there a difference between:
<span id="test" class="one two"></span>
and
<span id="test" class="two one"></span>
If there are conflicting CSS rules on these classes does the order matter?
Are there any APIs in jQuery to reorder? When I call addClass()
does it always go on the end?
The order doesn't matter.
http://jsfiddle.net/rc8Yu/
css precedence
The important part here is
If two rules are equal in all of the above, the one declared last wins. CSS embedded in the html always come after external stylesheets regardless of the order in the html
The order of the classes in HTML doesn't not matter, but the order inside the CSS does matter. For example, if you had:
span.one { color: red }
span.two { color: blue }
Both spans with class="one two"
and class="two one"
would produce blue text, because the class "two" is defined last. But if we changed that to
span.two { color: blue }
span.one { color: red }
and did the same thing, both spans would now have red text because the class "one" is defined last. Also keep in mind that the ID will override both of those classes no matter what, so if I defined:
span#test { color: green }
and added id="test"
, then the spans will always have green text no matter where in the document the classes and ID selector are defined, because an ID is naturally more specific than a class (other instances can make a class more specific than an ID, etc).
Since this is true, the order of your classes as assigned by jQuery is completely irrelevant. You should not need to worry about reordering them, but yes, addClass does just add the class to the end of the list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With