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

[Solved] document.getElementById problem

Hello there, I want to change the size of the words in a sentence but when I start the function work just the first one. I used document.getElementById to select the words. Why? Bellow there is the code.

Thank you!

<span id="highlight">Nullam</span> sed lectus nec velit vehicula vulputate et in nisi. In pulvinar enim turpis. <span id="highlight">Curabitur</span> rhoncus consequat diam, sit amet feugiat nulla sollicitudin ut.

<button onclick="newSize()">span</button>
function newSize() {
  let y = document.getElementById("highlight");
  if (y.style.fontSize == "2em") {
    y.style.fontSize = "1em"
  } else {
    y.style.fontSize = "2em";
  }

}

1 Answer

It only highlights the first word because you're using an id to select the words. An id is unique, meaning that you can't have two id's with the same name on the same page. If you search the DOM for an id, it will stop as soon as it find one that matches, in your case, the first id with the name highlight is the span that contains the word Nullam. Because of this, this will be the only highlighted word. You should be using class as selector instead.

<span class="highlight">Nullam</span> sed lectus nec velit vehicula vulputate et in nisi. In pulvinar enim turpis. <span class="highlight">Curabitur</span> rhoncus consequat diam, sit amet feugiat nulla sollicitudin ut.
function newSize() {
  let y = document.getElementsByClassname("highlight");
  y.style.fontSize = "2em";
}

Also your if/else statement is unneccesary in this situation

I want also avoid the function and bring back the size to 1em with a second click. Anyway I change my code with your code but does not work.

https://codepen.io/coswise/pen/zzZBwq

I see, it makes sense then. I made a codepen for you here: https://codepen.io/stekmo/pen/XgMjmg Since there can be more items to change the style of, it you have to iterate through each of them.

thank you very much!