javascript中的NodeList对象 [英] NodeList object in javascript
问题描述
任何人都可以告诉我NodeList是什么类型的对象。我读到它是一个类似数组的对象,它可以通过括号表示法访问,例如 var a = someNode.childNode [0];
。这是怎么可能的,因为通过括号表示我们只能访问一个对象的属性,因为我知道我们不能拥有
Can anyone tell me what kind of object the NodeList is. I read that it is an array-like object and that it can be accessed via bracket notation, for example var a = someNode.childNode[0];
. How is this possible since via bracket notation we can only access to the properties of an object, and as i know we can not have
推荐答案
A NodeList
是 DOM元素
的集合。它就像一个数组(但它不是)。要使用它,您必须将其转换为常规JavaScript数组。以下代码片段可以为您完成工作。
A NodeList
is collection of DOM elements
. It's like an array (but it isn't). To work with it, you must turn it into a regular JavaScript array. The following snippet can get the job done for you.
const nodeList = document.getElementsByClassName('.yourClass'),
nodeArray = [].slice.call(nodeList);
更新:
// newer syntax
const nodeList = Array.from(document.querySelectorAll('[selector]'))
// or
const nodeList = [...document.querySelectorAll('[selector]')]
这篇关于javascript中的NodeList对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!