问题
A javaScript object does not have a length property, but the returned value of querySelectorAll
has a length property, indicating that it's an array. But if we check it by Array.isArray()
then it returns false, proving that it is not an array. What type of data is it then?
var obj1 = {
fname: "Mirajul",
lname: "Momin",
age: 24
};
console.log(obj1.length);
var paraList = document.querySelectorAll("p");
console.log(paraList.length);
console.log(Array.isArray(paraList));
<p>This is paragraph one</p>
<p>This is paragraph two</p>
<p>This is paragraph three</p>
<p>This is paragraph four</p>
回答1:
The Element method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.
For the differences please visit: Difference between HTMLCollection, NodeLists, and arrays of objects
You can use Spread syntax to make that as an array:
var obj1 = {
fname: "Mirajul",
lname: "Momin",
age: 24
};
console.log(obj1.length);
var paraList = [...document.querySelectorAll("p")];
console.log(paraList.length);
console.log(Array.isArray(paraList));
<p>This is paragraph one</p>
<p>This is paragraph two</p>
<p>This is paragraph three</p>
<p>This is paragraph four</p>
回答2:
From documentation, "A non-live NodeList
containing one Element
object for each element that matches at least one of the specified selectors or an empty NodeList
in case of no matches."
You can check more about it at https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
回答3:
querySelectorAll() returns an array of objects with the elements that match the specified group of selectors.
.isArray() will return false because it returns object not array
Syntax:
var elms = document.querySelectorAll('selectors');
- 'selectors' is a string containing one or more CSS selectors separated by commas.
- elms is an array with the selected HTML elements.
Example, gets an Array with the content of LI tags with class='sites', and the tags with class='note' within element with id='dv1', then it displays their content:
Read the blog to better understand the querySelectorAll
https://coursesweb.net/javascript/queryselector-queryselectorall
来源:https://stackoverflow.com/questions/52128519/what-type-of-data-does-queryselectorall-return