Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Challenge: Query and Select DOM Elements | DOM Manipulation for Interactive Web Development
Advanced JavaScript Mastery

book
Challenge: Query and Select DOM Elements

Task

You have a shopping list in your HTML, and you need to select specific elements using various DOM querying methods.

  1. Select by ID: Select the <h1> element with the ID title;

  2. Select by Class: Select all elements with the class item;

  3. Select by Tag: Select all <li> elements;

  4. Select the First Matching Element: Select the first <li> element with the class item;

  5. Select All Matching Elements: Select all <li> elements with the class item.

html

index.html

css

index.css

js

index.js

copy
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="index.css" />
</head>
<body>
<h1 id="title">Shopping List</h1>
<ul>
<li class="item">Milk</li>
<li class="item">Eggs</li>
<li class="item">Bread</li>
<li class="item">Butter</li>
</ul>
<!-- Display Results -->
<div>
<p id="selected-title"></p>
<p id="selected-items-count"></p>
<p id="first-li-tag"></p>
<p id="first-item"></p>
<p id="all-items-count"></p>
</div>
<script src="index.js"></script>
</body>
</html>
  • Use getElementById to select the <h1> element with the ID title;

  • Use getElementsByClassName to select all elements with the class item;

  • Use getElementsByTagName to select all <li> elements;

  • Use querySelector to select the first <li> element with the class item;

  • Use querySelectorAll to select all <li> elements with the class item.

html

index.html

css

index.css

js

index.js

copy
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="index.css" />
</head>
<body>
<h1 id="title">Shopping List</h1>
<ul>
<li class="item">Milk</li>
<li class="item">Eggs</li>
<li class="item">Bread</li>
<li class="item">Butter</li>
</ul>
<!-- Display Results -->
<div>
<p id="selected-title"></p>
<p id="selected-items-count"></p>
<p id="first-li-tag"></p>
<p id="first-item"></p>
<p id="all-items-count"></p>
</div>
<script src="index.js"></script>
</body>
</html>

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 2. Kapittel 3

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

We use cookies to make your experience better!
some-alt