wenqili / knowtebook

0 stars 0 forks source link

DOM notes #16

Open wenqili opened 5 years ago

wenqili commented 5 years ago
// destructuring
const arr = [...document.querySelectorAll('p')];
wenqili commented 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.

wenqili commented 5 years ago

Relative searches

Like find in jQuery

const div = document.querySelector('#container');
div.querySelectorAll('p')  // finds all <p> tags in #container only
wenqili commented 5 years ago

Alias to avoid verbose

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.