Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript and the DOM (Retiring) Getting a Handle on the DOM Selecting by Id

Vic Mercier
Vic Mercier
3,276 Points

id

We could select multiple element on a page using document.getElementById method?

js/app.js
const my = document.getElementById("lol");
my.style.color = "red";
index.html
<!DOCTYPE html>
<html>
  <h1 id  = "lol">Sébastien</h1>
  <h2 id  = "lol">Victor</h2>
  <script src= "js/app.js"></script>
</html>

1 Answer

First things first, in HTML IDs values should be unique in every single page. You cannot have both your h1 and h2 with an ID of "lol". You should change that on the h2 (or the h1) or use a class instead.

So, you have two options:

  1. <h1 id="lol">Sébastien</h1> <h2 id="rotfl">Victor</h2>
  2. <h1 class="lol">Sébastien</h1> <h2 class="lol">Victor</h2>

Thus, in JavaScript, you can only select one element on a page with getElementById