Working with the DOM
To interact with elements on a web page, you need to access them first. JavaScript provides several methods to select elements by their various attributes.
By ID
You can select an element by its unique id
attribute using the getElementById
method.
let element = document.getElementById("myElement");
By Class Name
To select elements by their class name, use the getElementsByClassName
method. It returns a collection of elements.
let elements = document.getElementsByClassName("myClass");
By Tag Name
The getElementsByTagName
method allows you to select elements by their tag name. It also returns a collection of elements.
let elements = document.getElementsByTagName("div");
By CSS Selector
The querySelector
method allows you to select elements using CSS selector syntax.
let element = document.querySelector(".myClass");
Task
We have created a basic HTML tribute page without CSS.
- Select the h1 element with the id attribute using the heading variable.
- Select the image element using querySelector using the variable image.
- Select all paragraphs with class para using the paras variable.