DEV Community

Discussion on: Native Javascript element selector best practice

Collapse
 
reegodev profile image
Matteo Rigon • Edited

you can use the native methods document.querySelector and document.querySelectorAll that respectively return the first or all the elements that match the CSS query selector you provide. It works almost identically to jQuery (there are some limitations when using pseudo-selectors though).

developer.mozilla.org/en-US/docs/W...

const el = document.querySelector('.someElementClass');

As they are Element methods, they can be used not only on document but on any Element to find their children

const parent = document.querySelector('.parent');
const children = parent.querySelectorAll('.children');

Some people even declare some shortcuts to access these methods quickly:

window.$ = document.querySelector;
window.$$ = document.querySelectorAll;

const header = $('h1');
const headersList = $$('h1');