The DOM is a programming interfaces for HTML and XML documents. This basically means that it helps represent the structure, style, and content of a document, in our case our HTML document, in the form of objects.
You may be thinking, why is it important to represent the HTML elements in the form of objects? You may have experience in an object-oriented programming language: Java, Python, C++, Ruby, Scala, and many more. "Objects" contain data that have attribute, properties, and methods.
We already have seen some attributes of HTML elements in our previous lab.
imgelement have attributes
height, and more.
hidden, and more.
The DOM can be represented by a tree structure where the leaves or nodes of the tree each represent an HTML element. Let's take a look at an example code
index.html <html> <head> <title>My Document</title> </head> <body> <h1>Header</h1> <p>Paragraph</p> </body> </html>
The DOM is not a programming language. It used to connect/access the document, HTML file, and its elements.
You don't have to do anything special to use the DOM. It is a staple in web development and is already loaded into popular browsers. We access the DOM by using the keyword
document.querySelector(selector): Finds HTML elements that match the selectors. When using this method, selectors are written in a similar manner as CSS selectors. Remember that
classname of an element. This will only return a single element. If there are multiple elements that match the same selector, only the first element will be returned.
document.querySelectorAll(selector): This works similarly to the
querySelectormethod but returns all elements that match the selector.
document.getElementById(idName): Finds the single element that matches the
You may notice that in each of these options, it is incredibly important to utilize the
class attribute to identify a single element.