querySelector
is pretty versatile! It can select elements by classes, IDs, attributes, and even more complex CSS selectors. Here are some quick examples:
- By ID:
document.querySelector('#myId')
- By Class:
document.querySelector('.myClass')
- By Tag:
document.querySelector('p')
- More complex selectors:
document.querySelector('div > p.myClass')
Keep in mind that querySelector
returns the first element that matches the given selector. If you want to get all elements that match a selector, you can use querySelectorAll
, which returns a NodeList.
For example:
// Returns the first element with the class 'myClass'
const singleElement = document.querySelector('.myClass');
// Returns a NodeList containing all elements with the class 'myClass'
const allElements = document.querySelectorAll('.myClass');
So, yeah, querySelector
and querySelectorAll
are pretty handy tools in your JavaScript toolbox.
