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!

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 Select a Page Element By Its ID

James Steele
James Steele
2,816 Points

Why assign to const?

in this video we create a constant and assign the element to it by finding it by id.

const myHeading = document.getelementbyid('myheading');

and then we use that to add an eventlistener to then trigger a function if clicked.


could we not just add the event listener directly?

i.e. document.getelementbyid('myheading').addeventlistener('click', () => {document.getelementbyid('myheading').style.color = 'red';}

What's the advantage of using a constant? Is it just to reduce the amount of typing because I find that I can just cut and paste from where I have written before and if I use a constant would I not have to keep referring to what that const was assigned to?

1 Answer

Steven Parker
Steven Parker
228,096 Points

You can select the element and add the listener at the same time, avoiding the variable. But since access to the element is going to be used again later (inside the handler), it addresses the "DRY" principle and also makes the code a bit easier to read.

// without variable, makes 2 calls to getElementById:
document.getElementById('myheading').addEventListener('click', () => {
    document.getElementById('myheading').style.color = 'red';

// with variable (just one call):
const myHeading = document.getElementById('myheading');
myHeading.addEventListener('click', e => {
    myHeading.style.color = 'red';