Conteúdo do curso
JavaScript Course for Beginners: Fundamentals and Practice
Sobre a Aula

Selecting Elements by ID, Class, and Tag

Welcome to the second lesson of Module 3! In this stage, you will deepen your understanding of how to select DOM (Document Object Model) elements precisely and efficiently, using specific methods for IDs, classes, and tags.

In web development, there is often a need to select specific elements on a page.

In JavaScript, we can use different methods for this selection, such as by ID, class, and tag.

In this explanation, let’s learn how to perform these selections clearly and efficiently.

Selecting by ID

An ID is a unique identifier assigned to an HTML element.

We can select an element by ID using the getElementById() method.

This method returns the element with the corresponding ID. It’s like each element has a unique “ID card.”

Code Example:

var element = document.getElementById("myElement");

Selecting by Class

A class is an attribute that can be shared by multiple HTML elements.

We can select elements by class using the getElementsByClassName() method.

This method returns a list of elements that have the specified class. It’s like having a “list of friends” with the same characteristic.

Code Example:

var elements = document.getElementsByClassName("myClass");

Selecting by Tag

A tag represents a type of HTML element, such as <div>, <p>, <h1>, and others.

We can select elements by tag using the getElementsByTagName() method.

This method returns a list of elements that have the specified tag. It’s like having a “collection of objects” of the same type.

Code Example:

var elements = document.getElementsByTagName("div");

Challenge:

  • Create a JavaScript script that creates three buttons on the web page.
  • Each button should have a different class: “red-button,” “blue-button,” and “green-button.”
  • Add a click event to each button.

When the user clicks a button, change the button’s color and display a message on the screen indicating the color of the clicked button.

Now that you’ve learned to select elements by ID, class, and tag, let’s take a step further in DOM manipulation.

The next lesson will guide you on how to modify the content and styles of elements, expanding your skills to create even more dynamic interfaces.

Entrar na conversa
Rolar para cima