javascript-course

Finding Elements Exercise

This exercise will help you practice finding elements in a webpage using JavaScript.

Example:

Let’s say we have an HTML document with the following code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Finding Elements Exercise</title>
  </head>
  <body>
    <p>This is a paragraph.</p>
    <p id="special-paragraph">This is a special paragraph.</p>
    <div class="square">This is a square.</div>
  </body>
</html>

Task:

  1. Find all the <p> elements:
const paragraphs = document.getElementsByTagName("p");
console.log(paragraphs);

This code will find all the <p> elements in the document and store them in a variable called paragraphs. You can then use a loop to iterate through the elements and access their properties and methods.

  1. Find the element with the ID “special-paragraph”:
const specialParagraph = document.getElementById("special-paragraph");
console.log(specialParagraph);

This code will find the element with the ID “special-paragraph” and store it in a variable called specialParagraph. You can then access its properties and methods directly.

  1. Find all elements with the class “square”:
const squares = document.getElementsByClassName("square");
console.log(squares);

This code will find all elements with the class “square” and store them in a variable called squares. You can then use a loop to iterate through the elements and access their properties and methods.

  1. Change the text of the first <p> element:
paragraphs[0].innerText = "This is the first paragraph.";

This code will change the text of the first <p> element to “This is the first paragraph.”.

  1. Change the background color of the element with the ID “special-paragraph”:
specialParagraph.style.backgroundColor = "red";

This code will change the background color of the element with the ID “special-paragraph” to red.

Additional Exercises:

By practicing these exercises, you will gain a better understanding of how to find and manipulate elements in a webpage using JavaScript.