Home  >  Article  >  WeChat Applet  >  4 ways to loop Nodelist Dom list in JS

4 ways to loop Nodelist Dom list in JS

php中世界最好的语言
php中世界最好的语言Original
2018-03-17 15:41:453029browse

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

    Image path causes webpack packaging error How to deal with

    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!

    Statement:
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn