JavaScript JavaScript and the DOM Getting a Handle on the DOM Select a Page Element By Its ID

Shung Chen
Shung Chen
6,521 Points

we can manipulate the button by its ID directly without selecting it first?

as title. wondering why we don't need this line

const myHeading = document.getElementById('myHeading');
const turnRed = document.getElementById('red');
const colorValue = document.getElementById('myTextInput');
//const changeButton = document.getElementById('changeButton'); // we don't need this line

changeButton.addEventListener('click', ()=>{
  myHeading.style.color = colorValue.value;
});

1 Answer

Steven Parker
Steven Parker
203,727 Points

The video does select the element this way, but in the video the button's ID is "MyButton".

If you're wondering why this might work in your own test code, it would be because your browser is internally creating variables for elements using their ID as a variable name. But this behavior should not be relied on. It might not be done in all types of browsers; and even when it is, it might stop working in future versions.