Home > Article > Web Front-end > HTML5 actual combat and analysis of classList attribute
I have introduced some newly added selectors in HTML5, namely querySelector(), querySelectorAll() and getElementsByClassName(). These three have their own unique functions. If necessary, you can read the relevant content in HTML5 actual combat and analysis. Today I will introduce to you the classList attribute.
What exactly does the classList attribute do? Let’s leave classList alone for now. We consider the question, that is, how do we delete one of the class names among elements with multiple class names? Menglong struggled with his brain and finally came up with a way to achieve it. Delete the class name meng among the three class names li, meng and long. The code is as follows
HTML code
<p class="li meng long">梦龙小站</p>
JavaScript code
//获取要删除类名meng的p var p = document.getElementsByTagName("p")[0]; //获取类名字符串并拆分成数组 var allClassName = p.className.split(" "); //找到要删除的类名 var i, len, pos = -1; for(i=0, len = allClassName.length; i < len; i++){ if(allClassName[i] == "meng"){ pos = i; break; } } //删除类名 allClassName.splice(pos, 1); alert(allClassName) //li,long //将其余的类名拼成字符串并重新添加到元素的类名中 p.className = allClassName.join(" ");
Preview effect
HTML code
<p class="li meng long">梦龙小站</p>
JavaScript code
//获取要删除类名meng的p var p = document.getElementsByTagName("p")[0]; alert(p.classList) //li meng long p.classList.remove("meng") alert("p.className: " + p.className) //p.className: li long
Preview effect
## 2. contains(value)
HTML Code<p class="li meng long">梦龙小站</p>
JavaScript code//获取要删除类名meng的p
var p = document.getElementsByTagName("p")[0];
alert(p.classList.contains("meng")) //true
alert(p.classList.contains("menglong")) //false
3. add(value)
HTML code<p class="li meng long">梦龙小站</p>
JavaScript code//添加类名 menglong
//获取要删除类名meng的p
var p = document.getElementsByTagName("p")[0];
p.classList.add("menglong");
alert("p.className: " + p.className) //p.className: li meng long menglong
Preview effect
## 4. toggle(value)
梦龙小站<p class="li meng long">梦龙小站</p>
//切换类名 meng
//获取要删除类名li的p
var p = document.getElementsByTagName("p");
var i, len;
for(i=0, len = p.length; i< len; i++){
p[i].classList.toggle("meng");
}
alert("p[0].className: " + p[0].className) //p[0].className: li long
alert("p[1].className: " + p[1].className) //p[1].className: li meng long
The classList attribute of HTML5 actual combat and analysis is introduced here. The accumulation of bit by bit is tomorrow’s success. If you learn a little HTML5 in one day, you will definitely learn it successfully one day. Thank you all for supporting Menglong Station. For more updates about HTML5, please pay attention to Menglong Station’s updates on HTML5 practice and analysis.
The above is the content of the classList attribute of HTML5 actual combat and analysis. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!