Open wenqili opened 5 years ago
The querySelectorAll
method differs from methods like getElementsByTagName
and getElementsByClassName
in that these methods return an HTMLCollection
which is a live collection, whereas querySelectorAll
returns a NodeList
which is static.
if you would do getElementsByTagName('p') and one \
would be removed from the document, it would be removed from the returned HTMLCollection as well. But if you would do querySelectorAll('p') and one \
would be removed from the document, it would still be present in the returned NodeList.
Like find
in jQuery
const div = document.querySelector('#container');
div.querySelectorAll('p') // finds all <p> tags in #container only
const $ = document.querySelector.bind(document);
$('#container');
const $$ = document.querySelectorAll.bind(document);
$$('p');
Any valid CSS selector will do and the only difference is querySelector
will return a single element whereas querySelectorAll
will return a static NodeList containing the found elements. If there are no elements found it will return an empty NodeList.