JavaScript Course

Selecting DOM Elements

getElementById()

getElementById() is a method that helps us select a single HTML element by its unique id attribute. id is a unique identifier assigned to an element, and it's often used to style or manipulate that specific element.

How to use getElementById():

  1. Get the element's id: Identify the unique ID assigned to the element you want to select.
  2. Pass the id to getElementById(): Use this syntax: document.getElementById("elementID")
  3. Store the selected element: Assign the result to a variable to access the element's properties and methods.

Example:

const myHeading = document.getElementById("mainHeading");
myHeading.style.color = "red"; // Changes the color of the element with ID "mainHeading"

Tips for remembering getElementById():

  • Think of it as "grab the element by its unique name."
  • Associate it with a door with a door number. getElementById() finds the door with the matching number and lets us access it.

Next up:

getElementsByClassName() and other ways to select elements...

getElementsByClassName()

Want to find a group of elements with the same class name? That's where getElementsByClassName() comes in!

How to use it?

It's simple:

  1. Get the class name of the elements you want.
  2. Pass it to getElementsByClassName(): document.getElementsByClassName("className")
  3. The result is a collection of all elements with that class.

Example:

const myButtons = document.getElementsByClassName("btn");
myButtons[0].style.backgroundColor = "blue"; // Changes the background color of the first button

Remember it easily:

Think of it as a "class roll call". getElementsByClassName() gathers all the elements that have the same class name, like students in a class.

Next Adventure:

Stay tuned for getElementsByTagName(), where we explore a powerful way to find elements based on their tag names...

getElementsByTagName()

Hey there, curious minds! Ready to dive into another way to select elements? Meet getElementsByTagName()!

What it does:

This nifty method grabs all the elements with a specific tag name. It's like having a superpower to find all the <p> tags or all the <button> tags in a snap.

How to use it:

It's as simple as this:

  1. Figure out the tag name of the elements you're looking for.
  2. Pass it to getElementsByTagName(): document.getElementsByTagName("tagName")
  3. Voila! You get a collection of all the elements with that tag name.

Example:

const myParagraphs = document.getElementsByTagName("p");
myParagraphs[0].innerHTML = "Hello, world!"; // Changes the text of the first paragraph

Tips for remembering:

Think of getElementsByTagName() as the "tag inspector". It scans through the web page and finds all the elements with a specific tag name, like a detective searching for clues.

Next stop:

Uncover the wonders of querySelector() and querySelectorAll() in our next adventure!

querySelector()

Find it Fast with Precision

If you want to zero in on a single HTML element by its ID, class, or other attributes, querySelector() is your go-to tool. It's a powerful way to select an element with precision.

How to use it:

It's like a GPS for elements:

  1. Identify the unique attribute or combination of attributes that identifies your target element.
  2. Use this syntax: document.querySelector("attributeSelector")
  3. The result is the first matching element.

Example:

const myHeader = document.querySelector("h1.main-heading");
myHeader.style.fontSize = "24px"; // Changes the font size of the h1 with class "main-heading"

Remember it with Ease:

Imagine querySelector() as a secret agent tasked with finding a specific person in a crowd. It uses its keen eyes to locate the target based on their unique characteristics.

Next Adventure:

Discover the power of querySelectorAll(), which can find multiple elements that match your criteria. It's like a search party for HTML elements!

querySelectorAll()

Grab Multiple Elements with Power

When you need to find and work with multiple HTML elements that share certain characteristics, querySelectorAll() steps up to the plate. It's like a net that scoops up all matching elements in one go.

How to use it:

Here's how you wield this mighty tool:

  1. Craft a selector that describes the attributes common to your target elements.
  2. Use this syntax: document.querySelectorAll("attributeSelector")
  3. The result is a collection of all matching elements.

Example:

const allButtons = document.querySelectorAll("button");
allButtons.forEach(button => button.style.color = "blue"); // Changes the color of all buttons

Remember it with Confidence:

Think of querySelectorAll() as a superhero with X-ray vision. It can scan through the entire web page and locate all the elements that match your criteria, just like a superhero finding all villains in a city.

Next Challenge:

Dive deeper into selecting elements by attribute values in our next quest. Stay tuned for the joy of precision targeting!

Selecting by Attribute Value

What is it?

Let's imagine we have a group of <div> elements on our web page, and each one has a different color. How can we select the <div> with the color "red"? That's where selecting by attribute value comes in!

How to do it?

There are several methods to select elements based on their attributes:

  • getAttribute(): Gets the value of a specified attribute for an element.
  • setAttribute(): Sets the value of a specified attribute for an element.
  • hasAttribute(): Checks whether an element has a specified attribute.

For example, to select the <div> with the color "red" using getAttribute():

const redDiv = document.querySelector("div[color=red]");

Remember it easily

  • Visualize: Imagine each attribute as a label attached to an element, like "color: red."
  • Short table:
Method Purpose
getAttribute() Get attribute value
setAttribute() Set attribute value
hasAttribute() Check for attribute existence

Going further

Selecting by attribute value is essential for targeting specific elements on a web page. This knowledge empowers you to manipulate and style your web elements with precision. Keep practicing and exploring other methods, such as selecting by multiple criteria. The possibilities are endless!

Selecting by Multiple Criteria

Hey there, JavaScript explorers! Let's take a step further and discover how to select HTML elements based on multiple criteria. It's like being a detective, gathering clues to find exactly what you're looking for!

h3. querySelectorAll() with Multiple Selectors

Imagine you want to find all elements with the class "btn" and the color "blue." It's like asking for all the buttons that are blue. You can use this magic formula:

const blueButtons = document.querySelectorAll("btn .blue");

This selects all elements with the class "btn" and also the class "blue." Think of it as putting two filters on your search.

h3. Combining Selectors

You can combine different selectors using commas. It's like stacking up multiple filters to narrow down your search. For example:

const clickableHeadings = document.querySelectorAll("h2, h3 a");

This finds all

and

elements, as well as all anchor () elements inside these headings. It's like searching for all big and small text that you can click on.

h3. Using Multiple Criteria in getElementsByTagName()

While less common, you can use multiple criteria in getElementsByTagName(). It's like a simplified version of querySelectorAll(). Here's how:

const myDivs = document.getElementsByTagName("div.container");

This finds all elements with the tag name "div" and the class "container." Remember, it's not as versatile as querySelectorAll().

h3. Ready for the Adventure Ahead?

Now that you're a master of multiple criteria selection, the next frontier awaits: Traversing the DOM. It's like exploring a vast web of elements, looking for hidden treasures. Get ready for the thrilling next steps!

Traversing the DOM

h3. What is Traversing the DOM?

Traversing the DOM (Document Object Model) is like exploring a virtual version of your web page. It allows you to navigate through the web page's structure, accessing and manipulating specific elements. Imagine it as a map that guides you through the web page's HTML elements.

h3. Why is Traversing the DOM Important?

Traversing the DOM unlocks the power to dynamically interact with your web page. You can:

  • Manipulate elements: Change their text, style, or attributes.
  • Add or remove elements: Inject new content or remove unnecessary elements.
  • Event handling: Assign event listeners to specific elements, such as click or hover events.

h3. Common Traversal Methods

  • parentNode: Moves up to the parent element.
  • childNodes: Returns a list of child elements.
  • nextSibling: Moves to the next sibling element.
  • previousSibling: Moves to the previous sibling element.
  • firstChild: Returns the first child element.
  • lastChild: Returns the last child element.

h3. Visualizing Traversal

Imagine a web page with a header (

), a paragraph (

), and a button (

Share Button