当前位置:网站首页>Native JS dynamically add and delete classes

Native JS dynamically add and delete classes

2022-06-22 10:36:00 Ah Fei

Native JS Dynamically add and delete classes

Because of the need to , Listen for click events for button groups ( Request to delegate with an event ), When a button is clicked , Add a class to the button accordingly ( Activate class ), Other buttons that have not been clicked will be removed from this category

There are three ways to add and remove classes

First get a dom object ( Also called dom Elements ), adopt document.getElement…… By several methods
Such as

<div id="box" class="foo"></div>
==>
<div id="box" class="foo bar"></div>
let el = document.getElementById("box");
  1. By class name , Get the name of the class : el.className, assignment : el.className = "foo bars" Will overwrite the original class

  2. Passing attribute , Get the name of the class : el.getAttribute("class"); assignment : el.setAttribute("class", "foo bar"); Will overwrite the original class

  3. Through the attribute node attributeNode( Poor performance , But it's compatible ie,getAttribute() ie Some versions of do not support )setAttributeNode() Method to add the specified attribute node to the element .
    If the specified property already exists , Then this method will replace it ., Get the name of the class : getAttributeNode("class").value, assignment :

    let  attr = document.createAttribute("class");
    attr.nodeValue = "foo bar";
    el.setAttributeNode(attr)
    
  4. adopt classList attribute , Get the name of the class el.classList; Append class name : el.classList.add("foo"); Delete class : el.calssList.remove("foo");

The above four methods , classList Most flexible , Better be easy to use , But not supported ie9 The following browsers , Poor compatibility

Sample code
html

<div id="btn-group">
	<div class="btn btn-active"> Button 1</div>
	<div class="btn"> Button 2</div>
	<div class="btn"> Button 3</div>
	<div class="btn"> Button 4</div>
</div>

js Code , Which USES ES6 grammar ( use ES6 Write concisely )

let myEventUtil = {
    
	//  Add listening Events 
	addEvent (element, type, handler) {
    
		if (element.addEventListener) {
    
			element.addEventListener(type, handler, false);
		} else if (element.attach){
     // ie
			element.attach("on"+ type, handler);
		} else {
    
			element['on' + type] = handler;
		}
	},
	getTarget (event) {
    
		let event = event || window.event;
		return event.target || event.srcElement;
	}
}
let my$ = id => document.getElementById(id);

let btnGroup = my$(“btn-group”);
myEventUtil.addEvent(btnGroup, 'on', function (ev) {
    
	//  To all  btn  Remove the active class  btn-active
	// console.log(this) ==>  It's a dom Elements  btnGroup 
	//  Can pass  el.children[i] Get the specific child elements 
	//  You can get the child elements by  el.classList.remove("className")  Delete class 
	// el.classList.add("className")  To add classes 
	
	//  Delete class 
	let len = this.children.length;
	for (let i = 0; i < len; i ++) {
    
		this.children[i].classList.remove("btn-active");
		// this.children[i].className = "btn"; //  Just use one of them 
	}
	//  Add the class ,  Get specific  btn  Add classes to it 
	myEventUtil.getTarget(ev).classList.add("btn-active"); 
	// myEventUtil.getTarget(ev).className = "btn"; //  Just use one of them 
});
原网站

版权声明
本文为[Ah Fei]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206221014084096.html