JavaScript JavaScript and the DOM Making Changes to the DOM Getting and Setting Text with textContent and innerHTML

Robert Rydlewski
Robert Rydlewski
3,759 Points

Hey, I have a question about this lesson.

So in Console, we select the heading element and assign the element to variable name "myHeading"
like that: let myHeading = document.querySelector('h1')

my question why we even bother to do it? if I can do everything without assing variable name ?? At least worked for me. When I don't assign variable and do

``myHeading.textContent''
it show my content

when I do

myHeading.textContent = "Robert Rydlewski''' . it changes my content so why we assign the variable ??

Can someone please explain to me my error of thinking.

Thanks

2 Answers

Steven Parker
Steven Parker
182,340 Points

Your browser is creating a variable for you based on the element ID, but this behavior might not the same in future versions or other browsers. So it's better to use the selector function.

You can, however, skip the variable creation if you only need to perform one operation like this:

document.querySelector('h1').textContent = "header message";
Robert Rydlewski
Robert Rydlewski
3,759 Points

Thanks, Steven, You're the man.