我如何为div添加一个类?

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

当前回答

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

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

其他回答

跨浏览器的解决方案

注意: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中添加类

同样值得一看的是:

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

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

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

使用.classList.add()方法:

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

这个方法比覆盖className属性更好,因为它不会删除其他类,如果元素已经有该类,也不会添加该类。

您还可以使用element切换或删除类。classList(参见MDN文档)。