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 JavaScript and the DOM (Retiring) Making Changes to the DOM Getting and Setting Text with textContent and innerHTML

Robert Rydlewski
Robert Rydlewski
3,828 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
231,236 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,828 Points

Thanks, Steven, You're the man.