How to use the querySelector method in javascript.
How does the document.querySelector() method work?
The most powerful thing about JavaScript is that you can use it to manipulate web pages. No other programming language has this capability. A foundational part is being able to select specific elements of a web page.
Understanding what’s known as the “DOM Tree” will help understanding this method.
All elements on a page are represented in a tree-like structure. The document
is the top most parent and all elements under it are children. Each element is
referenced as a “node”, which is an object that contains the data for that HTML
element.
.querySelector()
The .querySelector()
method is a simple way to select elements of a page.
By using the .querySelector()
method on the document
you can target any HTML
node on the page. It takes one parameter, a string of
CSS selector syntax, and
returns
the first node that matches the provided selector.
const title = document.querySelector(‘.article-title’);
//<h2>My Title</h2>
Keep in mind that it only returns one element, which is the first one that was
matched while traversing the DOM tree. If you want to return every element that
matches the provided selection use the .querySectorAll()
method.
.querySelectorAll()
The .querySelectorAll()
method returns an array of all elements that match the
provided selector.
const title = document.querySelectorAll(‘.article-title’);
// [h2.article-title, h2.article-title, h2.article-title];
Scoped querySelector
When using document.querySelector()
the traversal starts at the document
node. This can be a really expensive operation if the document has many nodes.
If you know the specific elements you want to select live under a specific node
then you can start at that node. This is because the querySelector method is
inherited through all html DOM nodes.
Important! All dom nodes inherit the .querySelector() and .querySectorAll() methods.
const articlesWrap = document.querySelector('.all-articles-wrap');
const allArticlesTitles = articlesWrap.querySelectorAll('.article-title');
By running the .querySelectorAll()
method on the articlesWrap
node the
traversal starts at that node rather than searching the whole document tree.
This can greatly improve the performance of this operation.
Have some feedback on this post? .