3.2 Manipulating HTML Elements
To manipulate our HTML elements, we need to access them first. For example, we can access elements by id with getElementById():
const element = document.getElementById(“navbar”);
In general, we can also retrieve elements by:
- tag name
- class name
- CSS selectors [i.e. document.queryAllSelectors();]
- HTML object collections
To access elements by tag name, use getElementsByTagName():
To access elements by class name, use getElementsByClassName():
To access elements by CSS selectors, we need to use querySelectorAll():
Here, queryAllSelectors() takes a string as the argument. It finds all elements with a CSS selector (id, class name, tag name, attributes, etc.) matching the argument (review CSS if you’ve gotten unfamiliar with selectors).
For instance, in the above example, “h1.title” is the CSS selector for all h1 tags with “title” as their class attribute. Hence, the above code will retrieve all h1 elements with class “title”.
A number of HTML objects (and object collections) can be accessed directly from document:
The above example retrieves the image element with id=”beach”. We retrieve the image elements from “images” using the same syntax as retrieving elements from maps and arrays.
Likewise, the following objects can be accessed in the same fashion:
Here’s a longer list: w3schools.com/js/js_htmldom_document.asp
Editing HTML Elements
document.getElementById(“p1”).innerHTML = “Hello World!”;
The innerHTML property allows us to change the HTML code within an element. Here, we set the contents of the “p1” element to the string “Hello World!”.
We can also change attributes of HTML elements. For example, we may set the link to an image:
document.getElementById(“sunriseImg”).src = “sunrise2.jpg”;
Or set the class of a paragraph tag:
document.getElementById(“p1”).class = “text”;
Insertion and Deletion
//create new p element; then text node let pTag = document.createElement(“p”); let text = document.createTextNode(“This is a new paragraph!”); //Append (insert) what we created pTag.appendChild(text); document.getElementById(“sect1”).appendChild(pTag);
- We need to create a new p-tag with createElement().
- Add text to our pTag, we have to create a text node with the value of the string we want to insert into our p-tag.
- We use appendChild() to insert our text node into our p-tag.
- We use appendChild() again to insert our p-tag into the div.
We can also delete elements. For instance, if we want to delete the p-tag we created in the last example, we can use removeChild():
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact firstname.lastname@example.org for inquiries.