JavaScript JavaScript and the DOM 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
203,722 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 => { = 'red';