
本文介绍了如何使用 JavaScript 修改 HTML 元素的 `class` 属性。重点讲解了如何通过 `querySelectorAll` 选取多个符合条件的元素,并使用循环来修改它们的 `className` 属性,从而实现批量修改 class 的功能。同时,展示了具体的代码示例和注意事项,帮助开发者更好地理解和应用该技术。
在 Web 开发中,经常需要使用 JavaScript 来动态修改 HTML 元素的属性,其中修改 class 属性是一个常见的需求。本文将详细介绍如何使用 JavaScript 修改元素的 class 属性,并提供一些实用的技巧和注意事项。
当需要修改多个具有相同 class 属性的元素时,querySelectorAll 方法结合循环是一种高效且常用的方法。querySelectorAll 可以选取所有匹配指定 CSS 选择器的元素,返回一个 NodeList 集合。
以下是一个示例,演示如何将所有同时拥有 dropdown-item 和 active 类的按钮元素的 class 属性修改为 dropdown-item:
立即学习“Java免费学习笔记(深入)”;
document.querySelectorAll(".dropdown-item.active").forEach(button => button.className = "dropdown-item");代码解释:
示例 HTML:
<select name="client" class="select form-select" id="id_client" style="display : none "> 
    <option value="1109">Charles</option> 
    <option value="1108">Fred</option> 
    <option value="1107">Lionel</option> 
    <option value="1106">Robert</option> 
    <option value="1105">Mike</option>
</select>
<div class="dropdown dselect-wrapper select">
    <button class="form-select " data-dselect-text="Charles" type="button" data-bs-toggle="dropdown" aria-expanded="false">
      Charles
    </button>
    <div class="dropdown-menu">
      <div class="d-flex flex-column">
        <input onkeydown="return event.key !== 'Enter'" onkeyup="dselectSearch(event, this, 'dselect-wrapper', 'form-select', false)" type="text" class="form-control" placeholder="Search" autofocus="">
        <div class="dselect-items" style="max-height:360px;overflow:auto">
          <button class="dropdown-item active" data-dselect-value="1109" type="button" onclick="dselectUpdate(this, 'dselect-wrapper', 'form-select')">Charles</button>
          <button class="dropdown-item" data-dselect-value="1108" type="button" onclick="dselectUpdate(this, 'dselect-wrapper', 'form-select')">Fred</button>
          <button class="dropdown-item" data-dselect-value="1107" type="button" onclick="dselectUpdate(this, 'dselect-wrapper', 'form-select')">Lionel</button>
          <button class="dropdown-item" data-dselect-value="1106" type="button" onclick="dselectUpdate(this, 'dselect-wrapper', 'form-select')">Robert</button>
          <button class="dropdown-item" data-dselect-value="1105" type="button" onclick="dselectUpdate(this, 'dselect-wrapper', 'form-select')">Mike</button>
        </div>
        <div class="dselect-no-results d-none">No results found</div>
      </div>
    </div>
  </div>CSS 样式 (可选):
.dropdown-item.active {
  background-color: red;
  color: white;
}本文介绍了如何使用 JavaScript 修改 HTML 元素的 class 属性,重点讲解了 querySelectorAll 方法结合循环的使用。通过掌握这些技巧,可以灵活地控制网页元素的样式,实现丰富的交互效果。在实际开发中,应根据具体情况选择合适的方法,并注意性能和兼容性问题。
以上就是使用 JavaScript 修改 HTML 元素的 Class 属性的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
 
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号