How to add a class to DOM element in JavaScript?

How to add a class to DOM element in JavaScript?

How to add a class for the div?
var new_row = document.createElement(‘div’);


Solution 1:

new_row.className = "aClassName";

Heres more info on MDN: className

Solution 2:

Here is working source code using function approach.

        .news{padding:10px; margin-top:2px;background-color:red;color:#fff;}
<div id="dd"></div>
            var countup = this;
            var newNode = document.createElement('div');
            newNode.className = 'textNode news content';
            newNode.innerHTML = 'this created div contains class while created!!!';

Solution 3:

Use the .classList.add() method:

const element = document.querySelector('');
<div class="foo"></div>

This method is better that 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 MDN docs).

Solution 4:

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

Solution 5:

var newItem = document.createElement('div'); = ('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]);

Solution 6:

Also worth taking a look at

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

Related:  Should I be removing console.log from production code?