简体   繁体   English

如何将 class 添加到 JavaScript 中的 DOM 元素?

[英]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.您可以使用任何给定的方法向元素添加类,这是检查、更改或删除它们的另一种方法。

  1. The className way - Simple way to add a single or multiple classes and remove or change all classes. className方式 - 添加单个或多个类并删除或更改所有类的简单方法。
  2. The classList way - The way to manipulate classes; classList方式 - 操作类的方式; add, change or remove a single or multiple classes at the same time.同时添加、更改或删除单个或多个类。 They can easily be changed at any time in your code.它们可以随时在您的代码中轻松更改。
  3. The DOM way - When writing code according to the DOM model, this gives a cleaner code and functions similar to the className way. DOM方式 - 当根据 DOM 模型编写代码时,这提供了类似于 className 方式的更清晰的代码和功能。

The className way通过className方式

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方式也可以使用。

The classList way classList方式

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方式完成。

The DOM way DOM方式

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

Cross-browser solution跨浏览器解决方案

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如何添加类

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

new_row.setAttribute("class", "YOUR_CLASS");

This will work ;-)这将工作;-)

source来源

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.

相关问题 如何在 DOM 元素中添加 javascript Class 的实例 - How to add instance of javascript Class in a DOM element 如果DOM元素包含类,我如何检入JavaScript? - How can I check in JavaScript if a DOM element contains a class? 如何使用 javascript 添加元素 class? - How can I add an element class with javascript? OO Javascript - 我应该让一个类将自己添加到DOM中还是让它返回一个元素然后添加到DOM中? - OO Javascript - Should I let a class add itself to the DOM or let it return an element to then add to the DOM? 如何在纯 JavaScript 中向元素添加和删除活动类 - How can I add and remove an active class to an element in pure JavaScript 如何使用 JavaScript 添加类的元素 - How I can add element's of class using JavaScript 如何通过 javascript 元素的 class 添加所有值? - How can I add all the values by the class of the element with javascript? 如何通过 javascript 将引导程序 class 添加到“按钮”元素? - How can I add a Bootstrap class to a 'Button' element through javascript? 如何使用javascript将类添加为元素的字符串? - how can i add class to an element as string with javascript? 如何使用Jquery或Javascript定位Appended元素,或者如何将该附加元素添加到DOM? - How can I either target an Appended element using Jquery or Javascript, or how can I add that appened element to the DOM?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM