我如何为div添加一个类?

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

当前回答

跨浏览器的解决方案

注意:Internet Explorer 9不支持classList属性。以下代码可以在所有浏览器中运行:

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

源码:如何在js中添加类

其他回答

如果要创建很多元素,您可以创建自己的基本createElementWithClass函数。

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

非常基本的我知道,但能够调用以下是少混乱。

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

而不是很多

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

一遍又一遍。

这个答案是很久以前写的/接受的。从那时起,更好,更全面的答案和例子已经提交。你可以向下滚动来找到它们。以下是为后人保留下来的公认的原始答案。


new_row.className = "aClassName";

这里有更多关于MDN: className的信息

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

下面是使用函数方法的工作源代码。

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

如果你想创建一个新的输入字段,例如文件类型:

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

输出为:<input type="file" class="w-95 mb-1">


如果你想用JavaScript创建一个嵌套的标签,最简单的方法是使用innerHtml:

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

输出将是:

<li>
    <span class="toggle">Jan</span>
</li>