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.

  1. Select the h1 element with the id attribute using the heading variable.
  2. Select the image element using querySelector using the variable image.
  3. Select all paragraphs with class para using the paras variable.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT