rhgiant — 2012-01-20T04:22:41-05:00 — #1
I'm wondering what is the safest way (in terms of cross-browsers issues) to add a class to an element.
paul_wilkins — 2012-01-20T05:38:42-05:00 — #2
If this is about CSS classes though, the simplest way is to add a space then your class name.
You can perform some checks beforehand too to see if the class name is already on the element.
The code at the following location provides some fairly good ways of doing that.
mjy — 2012-01-20T22:05:50-05:00 — #3
Assuming you're talking about CSS classes, you could for example add the "hilite" class to the element represented by the object e, as follows:
/* 'class' attribute contains no other class names: */
e.className = "hilite";
/* 'class' attribute already contains one or more class names, so a space separator is needed: */
e.className += " hilite";
rhgiant — 2012-01-24T10:56:14-05:00 — #4
I was wondering if the snipplr.com snippet would add class if element has no class attribute. Does the element have to already have a class="" or will it automatically add it if none is found?
paul_wilkins — 2012-01-24T17:16:59-05:00 — #5
Yes it will.