Skip to main content

Return the DOM element applied css classes as an Array.

function getClasses(element) {
  var result = [];
  var htmlClass = element.className;

  if (htmlClass && htmlClass.length > 0) {
    var htmlClasses = htmlClass.split(' ');
    for (var i = 0; i < htmlClasses.length; i++) {
      if (htmlClasses[i].length > 0) {
        result.push(htmlClasses[i]);
      }
    }
  }
  return result;
}

function addClass(element, name) {
  var htmlClasses = getClasses(element);

  for (var i = 0; i < htmlClasses.length; i++) {
    if (name.toLowerCase() === htmlClasses[i].toLowerCase()) {
      return;
    }
  }

  htmlClasses.push(name);
  element.className = htmlClasses.join(' ');
}

// Usage:
getClasses(document.getElementById("content"));
addClass(document.getElementById("content"), "className");