393

How do I add a class for the div?

var new_row = document.createElement('div');
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
wow
  • 7,989
  • 17
  • 53
  • 63

12 Answers12

612

This answer was written/accepted a long time ago. Since then better, more comprehensive answers with examples have been submitted. You can find them by scrolling down. Below is the original accepted answer preserved for posterity.


new_row.className = "aClassName";

Here's more information on MDN: className

Darko
  • 38,310
  • 15
  • 80
  • 107
  • 7
    what about setting multiple class names? – Simon Apr 21 '14 at 21:57
  • 8
    @Sponge `new_row.className = "aClassName1 aClassName2";` its just an attribute, you can assign any string you like, even if it makes for invalid html – Darko Apr 29 '14 at 09:47
  • 38
    I also would recommend `new_row.classList.add('aClassName');` as you can then add multiple class names – StevenTsooo Dec 28 '14 at 23:09
  • @StevenTsooo Note that `classList` is [unsupported](http://caniuse.com/#feat=classlist) in IE9 or below. – dayuloli Jan 07 '15 at 16:19
  • Is there a way to create an element with a classname in one line of code - and still get a reference to the element? for example: myEL = document.createElement('div').addClass('yo')' will not work. – Kokodoko Dec 30 '15 at 12:28
  • @StevenTsooo It's also important to note that no version of IE supports multiple values for classList.add() or classList.remove(). Edge finally adds support for multiple values for the classList property. – Cody Moncur Feb 13 '16 at 06:49
  • if you just created a DOM element or you are sure that it has no class names, using `className` seems to be more performant – Serge Eremeev Apr 20 '17 at 15:47
  • this answer shouldn't be accepted. the question was about _adding_ a class. say you have an element `myDiv` that points to this HTML via DOM: `
    ...
    `. To me, the semantics of adding some class (say `c`) to `myDiv` should change the HTML to have all 3 classes. This solution overwrites the pre-existing classes `.classList.add()` is the correct answer. PLEASE CONSIDER CLARIFYING THE DELETION SIDE-EFFECTS. this answer is still useful, but as-is, it is misleading
    – acat Feb 07 '22 at 01:31
  • @acat this answer is 13 years old so a bit late to the game. The original asker deemed that this answer satisfied their requirements hence marked it with a tick. Feel free to upvote other answers like the one below if they suit you better but you dont get to tell the OP what was going through their brain and what they actually meant by the word adding. – Darko Feb 08 '22 at 02:06
  • @DarkoZ the most recent edit is a little over 2 years old. Admittedly I missed the original answer date and only noticed the Dec 2019 date. Regardless, this answer is going to be what appears first when someone searches for something like "adding a class via DOM". I only made my suggestion in the context that an answer is something that's going to continue to affect the entire community, not just the OP. I do appreciate how explosively web tech has changed and 13 years is a long time. Great answer for 13 yrs ago. Since it's still a living doc, please do consider an edit or addition – acat Feb 08 '22 at 03:03
89

Use the .classList.add() method:

const element = document.querySelector('div.foo');
element.classList.add('bar');
console.log(element.className);
<div class="foo"></div>

This method is better than overwriting the className property, because it doesn't remove other classes and doesn't add the class if the element already has it.

You can also toggle or remove classes using element.classList (see the MDN documentation).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
  • Correct. But this doesn't really matter in the case of the OP, as they are asking how to add a class to a newly created element. – Jules Colle Nov 29 '22 at 19:08
41

3 ways to add a class to a DOM element in JavaScript

There are multiple ways of doing this. I will show you three ways to add classes and clarify some benefits of each way.

You can use any given method to add a class to your element, another way to check for, change or remove them.

  1. The className way - Simple way to add a single or multiple classes and remove or change all classes.
  2. The classList way - The way to manipulate classes; add, change or remove a single or multiple classes at the same time. They can easily be changed at any time in your code.
  3. The DOM way - When writing code according to the DOM model, this gives a cleaner code and functions similar to the className way.

The className way

This is the simple way, storing all classes in a string. The string can easily be changed or appended.

// Create a div and add a class
var new_row = document.createElement("div");
new_row.className = "aClassName";

// Add another class. A space ' ' separates class names
new_row.className = "aClassName anotherClass";
// Another way of appending classes 
new_row.className = new_row.className + " yetAClass";

If an element has a single class, checking for it is simple:

// Checking an element with a single class
new_row.className == "aClassName" ;
if ( new_row.className == "aClassName" )
    // true

Removing all classes or changing them is very easy

// Changing all classes
new_row.className = "newClass";

// Removing all classes
new_row.className = "";

Searching for or removing a single class when multiple classes are used is difficult. You need to split the className string into an array, search them through one by one, remove the one you need and add all others back to your element. The classList way addresses this problem and can be used even if the class was set the className way.

The classList way

It is easy to manipulate classes when you need to. You can add, remove or check for them as you wish! It can be used with single or multiple classes.

// Create a div and add a class
var new_row = document.createElement("div");
new_row.classList.add( "aClassName" );

// Add another class
new_row.classList.add( "anotherClass" );
// Add multiple classes
new_row.classList.add( "yetAClass", "moreClasses", "anyClass" );

// Check for a class
if ( new_row.classList.contains( "anotherClass" ) )
    // true

// Remove a class or multiple classes
new_row.classList.remove( "anyClass" );
new_row.classList.remove( "yetAClass", "moreClasses" );

// Replace a class
new_row.classList.replace( "anotherClass", "newClass" );

// Toggle a class - add it if it does not exist or remove it if it exists
new_row.classList.toggle( "visible" );

Removing all classes or changing to a single class is easier done the className way.

The DOM way

If you write code the DOM way, this looks cleaner and stores classes in a string by setting the class attribute.

// Create a div, add it to the documet and set class
var new_row = document.createElement( "div" );
document.body.appendChild( new_row );
new_row.setAttribute( "class", "aClassName anotherClass" );

// Add some text
new_row.appendChild( document.createTextNode( "Some text" ) );

// Remove all classes
new_row.removeAttribute( "class" );

Checking for a class is simple, when a single class is being used

// Checking when a single class is used
if ( new_row.hasAttribute( "class" ) 
    && new_row.getAttribute( "class" ) == "anotherClass" )
    // true

Checking for or removing a single class when multiple classes are used uses the same approach as the className way. But the classList way is easier to accomplish this and can be used, even if you set it the DOM way.

Hasse Björk
  • 1,431
  • 13
  • 19
38

Here is working source code using a function approach.

<html>
    <head>
        <style>
            .news{padding:10px; margin-top:2px;background-color:red;color:#fff;}
        </style>
    </head>

    <body>
    <div id="dd"></div>
        <script>
            (function(){
                var countup = this;
                var newNode = document.createElement('div');
                newNode.className = 'textNode news content';
                newNode.innerHTML = 'this created div contains a class while created!!!';
                document.getElementById('dd').appendChild(newNode);
            })();
        </script>
    </body>
</html>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sunny S.M
  • 5,768
  • 1
  • 38
  • 38
  • 8
    So? It serves as an example, there's nothing wrong with that. – Carey Dec 27 '15 at 23:05
  • Re *"while created"*: Do you mean *"while being created"*? Respond by [editing your answer](https://stackoverflow.com/posts/31431244/edit), not here in comments. Thanks in advance. – Peter Mortensen Jan 29 '20 at 10:04
  • An explanation would be in order. For example, what do you mean by *"a function approach"*? Can you elaborate (by [editing your answer](https://stackoverflow.com/posts/31431244/edit), not here in comments)? Thanks in advance. – Peter Mortensen Jan 29 '20 at 10:07
8

If doing a lot of element creations, you can create your own basic createElementWithClass function.

function createElementWithClass(type, className) {
  const element = document.createElement(type);
  element.className = className
  return element;
}

Very basic I know, but being able to call the following is less cluttering.

const myDiv = createElementWithClass('div', 'some-class')

as opposed to a lot of

 const element1 = document.createElement('div');
 element.className = 'a-class-name'

over and over.

jedensuscg
  • 103
  • 1
  • 4
4

If you want to create multiple elements all with in one method.

function createElement(el, options, listen = [], appendTo){
    let element = document.createElement(el);
    Object.keys(options).forEach(function (k){
       element[k] = options[k];
    });
    if(listen.length > 0){
        listen.forEach(function(l){
           element.addEventListener(l.event, l.f);
        });
    }
    appendTo.append(element);
}


let main = document.getElementById('addHere');
createElement('button', {id: 'myBtn', className: 'btn btn-primary', textContent: 'Add Alert'}, [{
  event: 'click',
  f: function(){
    createElement('div', {className: 'alert alert-success mt-2', textContent: 'Working' }, [], main);
  }
}], main);
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">

<div id="addHere" class="text-center mt-2"></div>
xNaii
  • 111
  • 1
  • 5
3
var newItem = document.createElement('div');
newItem.style = ('background-color:red'); 
newItem.className = ('new_class');
newItem.innerHTML = ('<img src="./profitly_files/TimCover1_bigger.jpg" width=50 height=50> some long text with ticker $DDSSD');
var list = document.getElementById('x-auto-1');
list.insertBefore(newItem, list.childNodes[0]);
Diego Slinger
  • 139
  • 11
2

Cross-browser solution

Note: The classList property is not supported in Internet Explorer 9. The following code will work in all browsers:

function addClass(id,classname) {
  var element, name, arr;
  element = document.getElementById(id);
  arr = element.className.split(" ");
  if (arr.indexOf(classname) == -1) { // check if class is already added
    element.className += " " + classname;
  }
}

addClass('div1','show')

Source: how to js add class

Community
  • 1
  • 1
Ravi Makwana
  • 2,782
  • 1
  • 29
  • 41
1
var new_row = document.createElement('div');

new_row.setAttribute("class", "YOUR_CLASS");

This will work ;-)

source

MEDZ
  • 2,227
  • 2
  • 14
  • 18
  • This is not a good solution as this approach does not work on all browsers. setAttribute is supported by only 60% of browsers in use today. https://caniuse.com/#search=setAttribute – Ragas Feb 02 '20 at 14:32
0

It is also worth taking a look at:

var el = document.getElementById('hello');
if(el) {
    el.className += el.className ? ' someClass' : 'someClass';
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
JoniS
  • 89
  • 9
  • 11
0

If you want to create a new input field with for example file type:

 // Create a new Input with type file and id='file-input'
 var newFileInput = document.createElement('input');

 // The new input file will have type 'file'
 newFileInput.type = "file";

 // The new input file will have class="w-95 mb-1" (width - 95%, margin-bottom: .25rem)
 newFileInput.className = "w-95 mb-1"

The output will be: <input type="file" class="w-95 mb-1">


If you want to create a nested tag using JavaScript, the simplest way is with innerHtml:

var tag = document.createElement("li");
tag.innerHTML = '<span class="toggle">Jan</span>';

The output will be:

<li>
    <span class="toggle">Jan</span>
</li>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mile Mijatović
  • 2,948
  • 2
  • 22
  • 41
0
<script>
    document.getElementById('add-Box').addEventListener('click', function (event) {
        let itemParent = document.getElementById('box-Parent');
        let newItem = document.createElement('li');
        newItem.className = 'box';
        itemParent.appendChild(newItem);
    })
</script>
Linkon
  • 1