我如何为div添加一个类?
var new_row = document.createElement('div');
我如何为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>
其他回答
同样值得一看的是:
var el = document.getElementById('hello');
if(el) {
el.className += el.className ? ' someClass' : 'someClass';
}
这个答案是很久以前写的/接受的。从那时起,更好,更全面的答案和例子已经提交。你可以向下滚动来找到它们。以下是为后人保留下来的公认的原始答案。
new_row.className = "aClassName";
这里有更多关于MDN: className的信息
如果你想创建一个新的输入字段,例如文件类型:
// 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>
下面是使用函数方法的工作源代码。
<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>
var new_row = document.createElement('div');
new_row.setAttribute("class", "YOUR_CLASS");
这将工作;-)
源