0

in jQuery you can do this:

$('#myElement').addClass('header');

how can I make it like this in pure javascript

var elem = document.getElementById('myElement');
elem.addClass('header');

So I want to make a small custom library which use the selector before the function instead of this:

function addClass(element, class) {
    element.className += ' ' + class;
}

which is called like this:

var elem = document.getElementById('myElement');
addClass(elem, 'header');

Is this possible and if it is how can I do that?

Sake Salverda
  • 625
  • 1
  • 6
  • 17
  • Why not just use jQuery instead of reinventing the wheel? – ElGavilan Aug 11 '14 at 12:16
  • possible duplicate of [How do I add a class to a given element?](http://stackoverflow.com/questions/507138/how-do-i-add-a-class-to-a-given-element) – gsiradze Aug 11 '14 at 12:17
  • FWIW, you can do exactly what you've proposed, except that you shouldn't use a variable named `class` because it's a reserved word. – Alnitak Aug 11 '14 at 12:19

2 Answers2

6

In HTML5 browsers, you can do this:

elem.classList.add('header');

I'd strongly suggest coding to modern standards wherever possible and use a shim to support older browsers as required. Eventually you'll be able to decommission the shims and you won't end up left with a load of crufty inefficient old code that was only written that way because of the old browsers.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
  • I know but why I should write my code double for browsers which allow classList? I mean I also have to write code for non html5 browsers – Sake Salverda Aug 11 '14 at 12:18
  • You don't have to write double code - there's plenty of shims already written. The point is that developers should use modern APIs whenever available and monkey patch the older browsers that don't have them. On newer browsers the modern code will just run natively and on older browsers the same code still works. See the link in my answer for more context. – Alnitak Aug 11 '14 at 12:20
1

You can write your own addClass method, something like:

function addClass(element, classname){
    var currentClassList = (element.className || '').split(/\s+/);
    currentClassList
     .push(currentClassList.indexOf(classname) > -1 ? '' : classname);
    element.className = currentClassList.join(' ').trim();
}

Here's a jsfiddle demo using this function

/*Note*/ A polyfill for Array.indexOf can be found here
/*Note 2*/ A polyfill for String.trim can be found here

KooiInc
  • 119,216
  • 31
  • 141
  • 177