Add a class to a tag

Hi,

I’m wondering what is the safest way (in terms of cross-browsers issues) to add a class to an element.

:slight_smile:

JavaScript is a higher-level language above those that use classes.

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.
http://snipplr.com/view/3561/addclass-removeclass-hasclass/

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:


if (!e.className)
  /* 'class' attribute contains no other class names: */
  e.className = "hilite";
else
  /* 'class' attribute already contains one or more class names, so a space separator is needed: */
  e.className += " hilite";

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?

:slight_smile:

Yes it will.