如何在JavaScript中将类添加到DOM元素?

问题描述 投票:224回答:8

如何为div添加课程?

var new_row = document.createElement('div');
javascript dom
8个回答
398
投票
new_row.className = "aClassName";

有关MDN的更多信息:className


28
投票

这里是使用函数方法的有效源代码。

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

27
投票

使用.classList.add()方法:

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

此方法最好重写className属性,因为它不会删除其他类,并且如果元素已经具有该类也不会添加该类。

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


14
投票

还有JavaScript的DOM方法:

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

1
投票
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]);

0
投票

也值得一看

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

0
投票

如果要使用例如file类型创建新的输入字段,则>

 // Create new Input with type file and id='file-input'
 var newFileInput = document.createElement('input');

 // New input file will have type file
 newFileInput.type = "file"; 

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

-4
投票

这也可以。

© www.soinside.com 2019 - 2024. All rights reserved.