DOM Manipulation: Intro to DOM
The DOM (Document Object Model) or HTML DOM is the standard object model and programming interface for programming. HTML DOM is the standard way to get, change, add or delete HTML Elements.
Finding HTML Elements
To manipulate out HTML DOM first we need to target our HTML Elements. We can achieve this by using:
- document.getElementById(id): finds an element by element id.
Example: document.getElementById(‘contact’) - document.getElementsByTagName(name): finds elements by tag name.
Example: document.getElementsByTagName(“H1”) - document.getElementsByClassName(name): finds elements by class name.
Example: document.getElementsByClassName(‘description’)
There is also two methods called querySelector and querySelectorAll which can be used in all three cases mentioned above. It is best practice to use querySelector and querySelectorAll to target desired elements. querySelector uses CSS selectors ( ‘#’ for id, ‘.’ for classes and ‘tag-name’ for HTML tags) and targets them respectively.
Practice
Open up a Javascript project (If you are unsure how to open a Javascript project, you can start here: Getting Started with Javascript). Then write the following codes:
in index.html:
<body> <h1>DOM Manipulation using JS</h1>
<p class="description">DOM Manipulation makes everything imagined possible</p>
<p id="contact">Javascript</p> <script src="./main.js"></script></body>
in main.js:
// target our elements
const header = document.querySelector('h1')
const description = document.querySelector('.description')
const contact = document.querySelector('#contact')// and querySelectorAll targets all elements of the same target
// we have two p tags in out html
const paragraphs = document.querySelectorAll('p')// now console log them and view our elements
console.log(header)
console.log(description)
console.log(contact)// this will returns a static NodeList
console.log(paragraphs)
if we visit our site we can see:
and if we open up our browser console:
Here, we can see querySelector and querySelectorAll successfully targeted our elements and logged in our console.
Read next chapter: DOM Manipulation: Manipulating HTML Elements using Javascript
Happy Coding.