¿Cómo agregar una clase al elemento DOM en JavaScript?


Cómo agregar una clase para el div?

var new_row = document.createElement('div');
Author: Michał Perłakowski, 2009-07-12

7 answers

new_row.className = "aClassName";

Aquí tienes más información sobre MDN: className

 322
Author: Darko Z,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-21 21:59:27

Aquí está trabajando el código fuente usando el enfoque de función.

<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 class while created!!!';
            document.getElementById('dd').appendChild(newNode);           
        })();
    </script>
</body>
</html>
 15
Author: Sunny S.M,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-15 13:05:33

Utilice el método .classList.add():

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

Este método es mejor que sobrescribir la propiedad className, porque no elimina otras clases, y no agrega la clase si el elemento ya la tiene.

También puede alternar o eliminar clases usando element.classList (ver MDN docs).

 12
Author: Michał Perłakowski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-14 14:43:33

También existe la forma DOM de hacer esto en 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 );
 11
Author: Hasse Björk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-28 06:52:49

También vale la pena echar un vistazo a

var el = document.getElementById('hello');
  if(el) {
    el.className += el.className ? ' someClass' : 'someClass';
  }
 -1
Author: Yoni,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-24 16:47:46
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]);
 -1
Author: Diego Slinger,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-02 18:30:55

Esto también funcionará.

$(document.createElement('div')).addClass("form-group")
 -2
Author: Muhammad Awais,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-03 06:45:05