如何为div
添加课程?
var new_row = document.createElement('div');
new_row.className = "aClassName";
有关MDN的更多信息:className
这里是使用函数方法的有效源代码。
<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>
使用.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)。
还有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 );
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]);
也值得一看
var el = document.getElementById('hello');
if(el) {
el.className += el.className ? ' someClass' : 'someClass';
}
如果要使用例如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>
这也可以。