Add a class to a tag


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


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.

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";
  /* 'class' attribute already contains one or more class names, so a space separator is needed: */
  e.className += " hilite";

I was wondering if the 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?


Yes it will.