[javascript] How can I add a class to a DOM element in JavaScript?

How do I add a class for the div?

var new_row = document.createElement('div');

This question is related to javascript dom

The answer is


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]);

Use the .classList.add() method:

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

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).


It is also worth taking a look at:

var el = document.getElementById('hello');
if(el) {
    el.className += el.className ? ' someClass' : 'someClass';
}

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>

There is also the DOM way of doing this in JavaScript:

// Create a div and set class
var new_row = document.createElement("div");
new_row.setAttribute("class", "aClassName");
// Add some text
new_row.appendChild(document.createTextNode("Some text"));
// Add it to the document body
document.body.appendChild(new_row);

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.


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>

This is better way

let new_row = document.createElement('div');
new_row.setAttribute("class", "classname");
new_row.setAttribute("id", "idname");

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

_x000D_
_x000D_
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);
_x000D_
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">

<div id="addHere" class="text-center mt-2"></div>
_x000D_
_x000D_
_x000D_


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


<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>

var new_row = document.createElement('div');

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

This will work ;-)

source