This time I will bring you 4 ways to loop the Nodelist Dom list in JS. What are the precautions for JS looping the Nodelist Dom list? Here are the actual cases, let’s take a look.
The examples in this article describe 4 ways to implement looping Nodelist Dom list in native JS. Share it with everyone for your reference, the details are as follows:
function $(id) { return document.getElementById(id); } var _PAGE = { timeListDom: $('timeList') }; var spanDoms = _PAGE.timeListDom.querySelectorAll('span'), domLen = spanDoms.length; // 第一种方式:原生for循环 for (var i = 0; i < domLen; i++) { var v = spanDoms[i]; // do something you want deal with DOM } // 第二种方式:Array 的 forEach函数 Array.prototype.forEach.call(spanDoms, function(v) { // do something you want deal with DOM }); // 第三种方式:Array 的 forEach函数 [].forEach.call(spanDoms, function(el) { // do something you want deal with DOM el.classList.remove('active'); }); // 第四种方式:继承Array 的 forEach函数 NodeList.prototype.forEach = Array.prototype.forEach; spanDoms.forEach(function(v) { // do something you want deal with DOM });
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
Detailed explanation of asynchronous loading of JavaScript
The above is the detailed content of 4 ways to loop Nodelist Dom list in JS. For more information, please follow other related articles on the PHP Chinese website!