”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 玩转classList API - SitePoint指南

玩转classList API - SitePoint指南

发布于2025-04-18
浏览:902

玩转classList API - SitePoint指南

Key Takeaways

  • The classList API, introduced in HTML5, provides methods and properties to manage class names of DOM elements, making it easier to add, remove, or toggle class names in JavaScript.
  • The classList API exposes methods such as add(), remove(), toggle(), contains(), item(), length, and toString() to perform operations on class names.
  • The classList API is widely supported among desktop and mobile browsers except for Internet Explorer, which started supporting this API from version 10.
  • The classList API simplifies the process of manipulating classes, making code cleaner and more efficient, and eliminating the need for complex string manipulation or using regular expressions to manage classes.
Since the creation of HTML and the birth of the first websites, developers and designers have tried to customize the look and feel of their pages. This need became so important that a standard, called CSS, was created to properly manage style and separate it from the content. In today’s highly interactive websites, you often need to add, remove, or toggle class names (usually referred to as “CSS classes”). Historically, dealing with these changes in JavaScript was slightly complicated because there were no built-in methods to perform these actions. This was the case until HTML5 introduced the classList API. In this article, we’ll discover how this API works and the methods it provides. Note: The term “CSS classes” is often used to refer to class names. These are the strings you put inside the class attribute of an element. However, there is an interesting article suggesting that the term is incorrect and you should avoid it. For the sake of brevity, in this article I’m going to use the term “classes” as a shortcut for “class names”.

What is the classList API?

The classList API provides methods and properties to manage class names of DOM elements. Using it, we can perform operations such as adding and removing classes, or checking if a given class is present on an element. The classList API exposes these methods and properties via an attribute of the DOM element, called classList. This attribute is of type DOMTokenList, and contains the following methods and properties:
  • add(class1, class2, ...): Adds one or more classes to the element’s class list.
  • contains(class): Returns true if the list of classes contains the given parameter, and false otherwise.
  • item(index): Returns the class at position index, or null if the number is greater than or equal to the length of the list. The index is zero-based, meaning that the first class name has index 0.
  • length: This is a read-only property that returns the number of classes in the list.
  • remove(class1, class2, ...): Removes one or more classes from the element’s class list.
  • toString(): Returns the element’s list of classes as a string.
  • toggle(class[, force]): Removes the given class from the class list, and returns false. If the class didn’t exist, it is added, and the function returns true. If the second argument is provided, it’ll force the class to be added or removed based on its truthiness. For example, setting this value to true causes the class to be added, regardless of whether or not it already existed. By setting this value to false, the class will be removed.
If you’re familiar with jQuery, you may think that the add() and remove() methods perform the same operation on multiple classes by passing a list of space-separated class names (for example add("red bold bigger")). This is not the case. To add or remove more classes at once, you’ve to pass a string for each classes (for example add("red", "bold", "bigger")). As I pointed out, the toggle() method has an optional argument that we can use to force a given action. In other words, if the second parameter of toggle() is false, it acts as the remove() method; if the second parameter is true, it acts as the add() method. Now that we’ve described the methods and the properties of this API, let’s see some examples of it in action. Each of the code samples shown below will perform an action assuming the presence of the following HTML element on the page.
 id="element" class="description">>

Adding a Class

To add the class name “red” to the class attribute of the element, we can write the following:
document.getElementById('element').classList.add('red');
// 
To add multiple classes, for example “red” and “bold”, we can write this:
document.getElementById('element').classList.add('red', 'bold');
// 
Note that if one of the provided classes was already present, it won’t be added again.

Removing a Class

To delete a class, for example “description”, we would write the following:
document.getElementById('element').classList.remove('description');
// 
To remove multiple classes at once, we write:
document.getElementById('element').classList.remove('description', 'red');
// 
Note that an error is not thrown if one of the named classes provided wasn’t present.

Toggling a Class

Sometimes we need to add or remove a class name based on a user interaction or the state of the site. This is accomplished using the toggle() method, as demonstrated below.
document.getElementById('element').classList.toggle('description');
// 

document.getElementById('element').classList.toggle('description');
// 

Retrieving a Class

The classList API provides a method of retrieving class names based on it’s position in the list of classes. Let’s say that we want to retrieve the first and the third classes of our element. We would write the following:
document.getElementById('element').classList.item(0);
// returns "description"

document.getElementById('element').classList.item(2);
// returns null

Retrieving the Number of Classes

Although not very common, there are cases where we may need to know the number of classes applied to a given element. The classList API allows us to retrieve this number through the length property as shown below:
console.log(document.getElementById('element').classList.length);
// prints 1

Determine if a Class Exists

Sometimes we may want to execute a given action based on the presence of a certain class. To perform the test we use the contains() method in the following fashion:
if (document.getElementById('element').classList.contains('description')) {
   // do something...
} else {
   // do something different...
}

Returning the Class List as a String

To return the list of classes as a string, we can use the toString() method, which is shown below.
console.log(document.getElementById('element').classList.toString());
// prints "description"

document.getElementById('element').classList.add('red', 'bold');
console.log(document.getElementById('element').classList.toString());
// prints "description red bold"

Browser Compatibility

The classList API is widely supported among desktop and mobile browsers except for Internet Explorer. IE began supporting this API starting in version 10. More specifically, you can use this API in Chrome 8 , Firefox 3.6 , Internet Explorer 10 , Safari 5.1 , and Opera 11.5 . As we’ve seen the classList API is very straightforward and, as you may guess, polyfilling it is not difficult. Creating your own polyfill should be straightfoward, but if you want something that already exists, you can use classList.js by Eli Grey.

Demo

This section provides a simple demo that allows you to experiment with the concepts explained in this article. The demo page contains two basic fields: a select element containing the methods and properties exposed by the API, and a textbox where we can write parameters to pass. As you’ll see, the demo doesn’t explicitly call the methods, but instead uses a simple trick (the use of the JavaScript apply() method), resulting in fewer lines of code. Because some browsers don’t support the API, we perform a check, and if it fails we display the message “API not supported”. If the browser does support the classList API, we attach a listener for the click event of the button so that once clicked, we execute the chosen method. A live demo of the code is available here.

>
  >
     charset="UTF-8">
     name="viewport" content="width=device-width, initial-scale=1.0"/>
    >ClassList API Demo>
    
      body
      {
        max-width: 500px;
        margin: 2em auto;
        font-size: 20px;
      }

      h1
      {
        text-align: center;
      }

      .hidden
      {
        display: none;
      }

      .field-wrapper
      {
        margin-top: 1em;
      }

      #log
      {
        height: 200px;
        width: 100%;
        overflow-y: scroll;
        border: 1px solid #333333;
        line-height: 1.3em;
      }

      .button-demo
      {
        padding: 0.5em;
        margin: 1em;
      }

      .author
      {
        display: block;
        margin-top: 1em;
      }
    >
  >
  >
    

>

ClassList API>

>

Live sample element>
id="showcase"> <span ">></span">>
>

>

Play area>
>
class="field-wrapper"> Methods and Properties:> add()> contains()> item()> length> remove()> toString()> toggle()> >
>
class="field-wrapper"> Parameters (use spaces for multiple parameters):> type="text" id="parameter">>
>
Execute>
>
id="d-unsupported" class="hidden">API not supported>

>

Log>
id="log">
>
Clear log> id="play-element" class="description">> if (!'classList' in document.createElement('span')) { document.getElementById('c-unsupported').classList.remove('hidden'); document.getElementById('execute').setAttribute('disabled', 'disabled'); } else { var playElement = document.getElementById('play-element'); var method = document.getElementById('method'); var parameter = document.getElementById('parameter'); var log = document.getElementById('log'); var showcase = document.getElementById('showcase'); document.getElementById('clear-log').addEventListener('click', function() { log.innerHTML = ''; }); document.getElementById('execute').addEventListener('click', function() { var message = method.value; if (method.value === 'length') { message = ': ' playElement.classList[method.value] } else { var result = playElement.classList[method.value].apply(playElement.classList, parameter.value.split(' ')); showcase.textContent = playElement.outerHTML; if (method.value === 'add' || method.value === 'remove' || method.value === 'toggle') { message = ' class "' parameter.value '"'; } else { message = ': ' result; } } log.innerHTML = message '
' log.innerHTML;
}); } > > >

Conclusions

In this article, we’ve learned about the classList API, its methods, and its properties. As we’ve seen, this API helps us in managing the classes assigned to a given element – and it is very easy to use and. This API is widely supported among desktop and mobile browsers, so we can use it safely (with the help of a polyfill if needed). As a last note, don’t forget to play with the demo to gain a better grasp of this API and its capabilities.

Frequently Asked Questions about ClassList API

What is the ClassList API and why is it important in JavaScript?

The ClassList API is a powerful tool in JavaScript that allows developers to manipulate the class attribute of HTML elements. It provides methods to add, remove, toggle, and check the presence of classes in an element’s class attribute. This is important because it simplifies the process of manipulating classes, making your code cleaner and more efficient. It also eliminates the need for complex string manipulation or using regular expressions to manage classes.

How does the ClassList API differ from the traditional methods of manipulating classes in JavaScript?

Traditional methods of manipulating classes in JavaScript involve directly accessing the className property of an element and performing string operations. This can be cumbersome and error-prone. The ClassList API, on the other hand, provides a more intuitive and straightforward way to manipulate classes. It offers specific methods for adding, removing, and toggling classes, making it easier and safer to use.

Can I use the ClassList API on all browsers?

The ClassList API is widely supported across all modern browsers. However, it’s worth noting that Internet Explorer 9 and older versions do not support the ClassList API. You can check the compatibility of the ClassList API on different browsers on websites like “Can I use”.

How do I add a class to an element using the ClassList API?

To add a class to an element using the ClassList API, you can use the add() method. Here’s an example:

element.classList.add("myClass");

In this example, “myClass” is the class you want to add to the element.

How do I remove a class from an element using the ClassList API?

To remove a class from an element using the ClassList API, you can use the remove() method. Here’s an example:

element.classList.remove("myClass");

In this example, “myClass” is the class you want to remove from the element.

How do I check if an element has a specific class using the ClassList API?

To check if an element has a specific class using the ClassList API, you can use the contains() method. Here’s an example:

if (element.classList.contains("myClass")) {
// do something
}

In this example, “myClass” is the class you want to check.

How do I toggle a class in an element using the ClassList API?

To toggle a class in an element using the ClassList API, you can use the toggle() method. Here’s an example:

element.classList.toggle("myClass");

In this example, “myClass” is the class you want to toggle. If the element already has the class, it will be removed. If it doesn’t have the class, it will be added.

Can I add or remove multiple classes at once using the ClassList API?

Yes, you can add or remove multiple classes at once using the ClassList API. You just need to pass the classes as separate arguments to the add() or remove() method. Here’s an example:

element.classList.add("class1", "class2", "class3");
element.classList.remove("class1", "class2", "class3");

In this example, “class1”, “class2”, and “class3” are the classes you want to add or remove.

Can I use the ClassList API with SVG elements?

Yes, you can use the ClassList API with SVG elements. However, it’s worth noting that this feature is not supported in Internet Explorer.

What are some common use cases for the ClassList API?

The ClassList API is commonly used for adding, removing, or toggling classes to show or hide elements, change their appearance, or trigger animations. It’s also used to check the presence of a class to perform some action. For example, you might want to check if an element has a “hidden” class before showing it, or you might want to add a “highlight” class to an element when it’s clicked.

最新教程 更多>
  • 如何在其容器中为DIV创建平滑的左右CSS动画?
    如何在其容器中为DIV创建平滑的左右CSS动画?
    通用CSS动画,用于左右运动 ,我们将探索创建一个通用的CSS动画,以向左和右移动DIV,从而到达其容器的边缘。该动画可以应用于具有绝对定位的任何div,无论其未知长度如何。问题:使用左直接导致瞬时消失 更加流畅的解决方案:混合转换和左 [并实现平稳的,线性的运动,我们介绍了线性的转换。这...
    编程 发布于2025-05-06
  • 如何从PHP中的数组中提取随机元素?
    如何从PHP中的数组中提取随机元素?
    从阵列中的随机选择,可以轻松从数组中获取随机项目。考虑以下数组:; 从此数组中检索一个随机项目,利用array_rand( array_rand()函数从数组返回一个随机键。通过将$项目数组索引使用此键,我们可以从数组中访问一个随机元素。这种方法为选择随机项目提供了一种直接且可靠的方法。
    编程 发布于2025-05-06
  • 为什么Microsoft Visual C ++无法正确实现两台模板的实例?
    为什么Microsoft Visual C ++无法正确实现两台模板的实例?
    The Mystery of "Broken" Two-Phase Template Instantiation in Microsoft Visual C Problem Statement:Users commonly express concerns that Micro...
    编程 发布于2025-05-06
  • 如何使用node-mysql在单个查询中执行多个SQL语句?
    如何使用node-mysql在单个查询中执行多个SQL语句?
    Multi-Statement Query Support in Node-MySQLIn Node.js, the question arises when executing multiple SQL statements in a single query using the node-mys...
    编程 发布于2025-05-06
  • 版本5.6.5之前,使用current_timestamp与时间戳列的current_timestamp与时间戳列有什么限制?
    版本5.6.5之前,使用current_timestamp与时间戳列的current_timestamp与时间戳列有什么限制?
    在时间戳列上使用current_timestamp或MySQL版本中的current_timestamp或在5.6.5 此限制源于遗留实现的关注,这些限制需要对当前的_timestamp功能进行特定的实现。 创建表`foo`( `Productid` int(10)unsigned not n...
    编程 发布于2025-05-06
  • Java的Map.Entry和SimpleEntry如何简化键值对管理?
    Java的Map.Entry和SimpleEntry如何简化键值对管理?
    的综合集合:在Java中介绍Java的Map.entry和SimpleEntry和SimpleEntry和SimpleEntry和SimpleEntry和SimpleEntry和SimpleEntry和SimpleEntry和SimpleEntry apry and Map。 地图。它具有两个通用...
    编程 发布于2025-05-06
  • 人脸检测失败原因及解决方案:Error -215
    人脸检测失败原因及解决方案:Error -215
    错误处理:解决“ error:((-215)!empty()in Function Multultiscale中的“ openCV 要解决此问题,必须确保提供给HAAR CASCADE XML文件的路径有效。在提供的代码片段中,级联分类器装有硬编码路径,这可能对您的系统不准确。相反,OPENCV提...
    编程 发布于2025-05-06
  • 如何使用不同数量列的联合数据库表?
    如何使用不同数量列的联合数据库表?
    合并列数不同的表 当尝试合并列数不同的数据库表时,可能会遇到挑战。一种直接的方法是在列数较少的表中,为缺失的列追加空值。 例如,考虑两个表,表 A 和表 B,其中表 A 的列数多于表 B。为了合并这些表,同时处理表 B 中缺失的列,请按照以下步骤操作: 确定表 B 中缺失的列,并将它们添加到表的末...
    编程 发布于2025-05-06
  • JavaScript计算两个日期之间天数的方法
    JavaScript计算两个日期之间天数的方法
    How to Calculate the Difference Between Dates in JavascriptAs you attempt to determine the difference between two dates in Javascript, consider this s...
    编程 发布于2025-05-06
  • 如何限制动态大小的父元素中元素的滚动范围?
    如何限制动态大小的父元素中元素的滚动范围?
    在交互式接口中实现垂直滚动元素的CSS高度限制,控制元素的滚动行为对于确保用户体验和可访问性是必不可少的。一种这样的方案涉及限制动态大小的父元素中元素的滚动范围。问题:考虑一个布局,其中我们具有与用户垂直滚动一起移动的可滚动地图div,同时与固定的固定sidebar保持一致。但是,地图的滚动无限期...
    编程 发布于2025-05-06
  • 在程序退出之前,我需要在C ++中明确删除堆的堆分配吗?
    在程序退出之前,我需要在C ++中明确删除堆的堆分配吗?
    在C中的显式删除 在C中的动态内存分配时,开发人员通常会想知道是否需要手动调用“ delete”操作员在heap-exprogal exit exit上。本文深入研究了这个主题。 在C主函数中,使用了动态分配变量(HEAP内存)的指针。当应用程序退出时,此内存是否会自动发布?通常,是。但是,即使在这...
    编程 发布于2025-05-06
  • 哪种在JavaScript中声明多个变量的方法更可维护?
    哪种在JavaScript中声明多个变量的方法更可维护?
    在JavaScript中声明多个变量:探索两个方法在JavaScript中,开发人员经常遇到需要声明多个变量的需要。对此的两种常见方法是:在单独的行上声明每个变量: 当涉及性能时,这两种方法本质上都是等效的。但是,可维护性可能会有所不同。 第一个方法被认为更易于维护。每个声明都是其自己的语句,使其...
    编程 发布于2025-05-06
  • Java中如何使用观察者模式实现自定义事件?
    Java中如何使用观察者模式实现自定义事件?
    在Java 中创建自定义事件的自定义事件在许多编程场景中都是无关紧要的,使组件能够基于特定的触发器相互通信。本文旨在解决以下内容:问题语句我们如何在Java中实现自定义事件以促进基于特定事件的对象之间的交互,定义了管理订阅者的类界面。以下代码片段演示了如何使用观察者模式创建自定义事件: args)...
    编程 发布于2025-05-06
  • 如何检查对象是否具有Python中的特定属性?
    如何检查对象是否具有Python中的特定属性?
    方法来确定对象属性存在寻求一种方法来验证对象中特定属性的存在。考虑以下示例,其中尝试访问不确定属性会引起错误: >>> a = someClass() >>> A.property Trackback(最近的最新电话): 文件“ ”,第1行, AttributeError: SomeClass...
    编程 发布于2025-05-06
  • 为什么使用固定定位时,为什么具有100%网格板柱的网格超越身体?
    为什么使用固定定位时,为什么具有100%网格板柱的网格超越身体?
    网格超过身体,用100%grid-template-columns 为什么在grid-template-colms中具有100%的显示器,当位置设置为设置的位置时,grid-template-colly修复了?问题: 考虑以下CSS和html: class =“ snippet-code”> g...
    编程 发布于2025-05-06

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3