Finding First Matching Element in DOM

HTML Webpages are represented as a DOM tree. But how do we find elements inside this tree? One of the requirements could be to find the first element matching the search criteria. This criterion is provided as a selector. The selector must be a valid CSS selector group represented as a DOMString.

In this video, you will learn how to find the first matching element inside DOM using method on the document object

Full Transcript

00:00 Let's have we have a HTML page represented as a DOM tree that contains two kinds of elements, the div element and the image element. And given this tree let's say we want to find out the first image element in the DOM tree. So looking at the top level document object, how do we find the first image element? The document model has a method called as querySelector which takes in one or more selectors as a group. The selectors must be a valid CSS string. For example, an image tag wrapped in the string is a valid CSS a selector. Or a warning class wrapped in a string is also valid CSS selector. The CSS selectors could be created from different types such as class selector, ID selector, NodeType selector and many more. For now, we'll keep our focus on finding the first image element using querySelector method on the document object. The querySelector method performs matching using depth-first pre-order traversal of the document node.

00:57 It starts from the first element in the document and iterates through the sequence of nodes. When it finds the first matching element, it stops the search and returns the element. If no matches are found, the method returns null. Let's see that in action now. Currently I've opened up the Google Chrome browser and opened up the unsplash.com webpage and I've also opened the Chrome dev tools next to it. First I will type document and as a type I can see the entire page is selected. Next we will use the querySelector method on DOM. We provide the image tag wrapped in a string making it a valid CSS selector. As we see the first image on Unsplash is selected. We could also fetch attributes from this result such as src to find out the image and compare that with what we see on Unsplash page. And we can confirm that bode day images are indeed same. And that's it.

01:53 If you work with JavaScript or any of the frameworks such as jQuery, angular or react, you have executed JavaScript on the browser. So the new course that we have launched is relevant for you. It's called Browser JavaScript and event loop. This course educates on how JavaScript is executed behind the scenes, and we'll cover various topics such as ExecutionContext, and event loop. You will have the opportunity to visually see every step of JavaScript code execution. Check out the course link in the description below to learn more about the course and let us know if you have any questions. Keep learning and see you next time.