如何在没有jQuery的情况下添加和删除JS中的类 [英] how to add and remove classes in JS without jquery

查看:65
本文介绍了如何在没有jQuery的情况下添加和删除JS中的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种快捷而安全的方法来添加和删除html元素中的类,而不使用jQuery。

它也应该在早期IE(IE8及更高版本)中工作。

解决方案

使用纯JavaScript将元素添加到元素的另一种方法

添加class:

  document.getElementById(div1)。classList.add(classToBeAdded); 

删除课程:

  document.getElementById(div1)。classList.remove(classToBeRemoved); 

注意:,但在IE< = 9或Safari< ; = 5.0


I'm looking for a fast and secure way to add and remove classes from an html element without jQuery.
It also should be working in early IE (IE8 and up).

解决方案

Another approach to add the class to element using pure JavaScript

For adding class:

document.getElementById("div1").classList.add("classToBeAdded");

For removing class:

document.getElementById("div1").classList.remove("classToBeRemoved");

Note: but not supported in IE <= 9 or Safari <=5.0

这篇关于如何在没有jQuery的情况下添加和删除JS中的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆