[英]How can I add a class to a DOM element in JavaScript?
How do I add a class for the div
?如何为div
添加 class ?
var new_row = document.createElement('div');
new_row.className = "aClassName";
这里有更多关于 MDN 的信息: className
Use the .classList.add()
method:使用.classList.add()
方法:
const element = document.querySelector('div.foo'); element.classList.add('bar'); console.log(element.className);
<div class="foo"></div>
This method is better than overwriting the className
property, because it doesn't remove other classes and doesn't add the class if the element already has it.此方法比覆盖className
属性要好,因为它不会删除其他类,并且如果元素已经具有该类,则不会添加该类。
You can also toggle or remove classes using element.classList
(see the MDN documentation ).您还可以使用element.classList
切换或删除类(请参阅MDN 文档)。
Here is working source code using a function approach.这是使用函数方法的工作源代码。
<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>
There are multiple ways of doing this.有多种方法可以做到这一点。 I will show you three ways to add classes and clarify some benefits of each way.我将向您展示三种添加类的方法并阐明每种方法的一些好处。
You can use any given method to add a class to your element, another way to check for, change or remove them.您可以使用任何给定的方法向元素添加类,这是检查、更改或删除它们的另一种方法。
This is the simple way, storing all classes in a string.这是一种简单的方法,将所有类存储在一个字符串中。 The string can easily be changed or appended.该字符串可以轻松更改或附加。
// Create a div and add a class
var new_row = document.createElement("div");
new_row.className = "aClassName";
// Add another class. A space ' ' separates class names
new_row.className = "aClassName anotherClass";
// Another way of appending classes
new_row.className = new_row.className + " yetAClass";
If an element has a single class , checking for it is simple:如果一个元素只有一个 class ,检查它很简单:
// Checking an element with a single class
new_row.className == "aClassName" ;
if ( new_row.className == "aClassName" )
// true
Removing all classes or changing them is very easy删除所有类或更改它们非常容易
// Changing all classes
new_row.className = "newClass";
// Removing all classes
new_row.className = "";
Searching for or removing a single class when multiple classes are used is difficult.当使用多个类时,搜索或删除单个类是很困难的。 You need to split the className string into an array, search them through one by one, remove the one you need and add all others back to your element.您需要将className字符串拆分为一个数组,一一搜索它们,删除您需要的一个并将所有其他字符串添加回您的元素。 The classList way addresses this problem and can be used even if the class was set the className way. classList方式解决了这个问题,即使类被设置为className方式也可以使用。
It is easy to manipulate classes when you need to.在需要时很容易操作类。 You can add, remove or check for them as you wish!您可以根据需要添加、删除或检查它们! It can be used with single or multiple classes.它可以与单个或多个类一起使用。
// Create a div and add a class
var new_row = document.createElement("div");
new_row.classList.add( "aClassName" );
// Add another class
new_row.classList.add( "anotherClass" );
// Add multiple classes
new_row.classList.add( "yetAClass", "moreClasses", "anyClass" );
// Check for a class
if ( new_row.classList.contains( "anotherClass" ) )
// true
// Remove a class or multiple classes
new_row.classList.remove( "anyClass" );
new_row.classList.remove( "yetAClass", "moreClasses" );
// Replace a class
new_row.classList.replace( "anotherClass", "newClass" );
// Toggle a class - add it if it does not exist or remove it if it exists
new_row.classList.toggle( "visible" );
Removing all classes or changing to a single class is easier done the className way.删除所有类或更改为单个类更容易通过className方式完成。
If you write code the DOM way, this looks cleaner and stores classes in a string by setting the class attribute.如果您以DOM方式编写代码,这看起来更清晰,并通过设置 class 属性将类存储在字符串中。
// Create a div, add it to the documet and set class
var new_row = document.createElement( "div" );
document.body.appendChild( new_row );
new_row.setAttribute( "class", "aClassName anotherClass" );
// Add some text
new_row.appendChild( document.createTextNode( "Some text" ) );
// Remove all classes
new_row.removeAttribute( "class" );
Checking for a class is simple, when a single class is being used当使用单个类时,检查类很简单
// Checking when a single class is used
if ( new_row.hasAttribute( "class" )
&& new_row.getAttribute( "class" ) == "anotherClass" )
// true
Checking for or removing a single class when multiple classes are used uses the same approach as the className way.在使用多个类时检查或删除单个类使用与className方法相同的方法。 But the classList way is easier to accomplish this and can be used, even if you set it the DOM way.但是classList方式更容易实现并且可以使用,即使您将其设置为DOM方式。
If doing a lot of element creations, you can create your own basic createElementWithClass function.如果要创建很多元素,您可以创建自己的基本 createElementWithClass 函数。
function createElementWithClass(type, className) {
const element = document.createElement(type);
element.className = className
return element;
}
Very basic I know, but being able to call the following is less cluttering.我知道的非常基本,但是能够调用以下内容就不那么混乱了。
const myDiv = createElementWithClass('div', 'some-class')
as opposed to a lot of相对于很多
const element1 = document.createElement('div');
element.className = 'a-class-name'
over and over.一遍又一遍。
If you want to create multiple elements all with in one method.如果您想用一种方法创建多个元素。
function createElement(el, options, listen = [], appendTo){ let element = document.createElement(el); Object.keys(options).forEach(function (k){ element[k] = options[k]; }); if(listen.length > 0){ listen.forEach(function(l){ element.addEventListener(l.event, lf); }); } appendTo.append(element); } let main = document.getElementById('addHere'); createElement('button', {id: 'myBtn', className: 'btn btn-primary', textContent: 'Add Alert'}, [{ event: 'click', f: function(){ createElement('div', {className: 'alert alert-success mt-2', textContent: 'Working' }, [], main); } }], main);
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous"> <div id="addHere" class="text-center mt-2"></div>
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]);
This is better way这是更好的方法
let new_row = document.createElement('div');
new_row.setAttribute("class", "classname");
new_row.setAttribute("id", "idname");
Note: The
classList
property is not supported in Internet Explorer 9 .注意: Internet Explorer 9不支持classList
属性。 The following code will work in all browsers:以下代码适用于所有浏览器:
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')
Source: how to js add class来源: js如何添加类
It is also worth taking a look at:也值得一看:
var el = document.getElementById('hello');
if(el) {
el.className += el.className ? ' someClass' : 'someClass';
}
If you want to create a new input field with for example file
type:如果要创建一个新的输入字段,例如file
类型:
// 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"
The output will be: <input type="file" class="w-95 mb-1">
输出将是: <input type="file" class="w-95 mb-1">
If you want to create a nested tag using JavaScript, the simplest way is with innerHtml
:如果要使用 JavaScript 创建嵌套标签,最简单的方法是使用innerHtml
:
var tag = document.createElement("li");
tag.innerHTML = '<span class="toggle">Jan</span>';
The output will be:输出将是:
<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>
这也行。
$(document.createElement('div')).addClass("form-group")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.