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
Shaun Russell
Front End Web Development Techdegree Graduate 18,510 PointsAssigning variables and using them inside functions
The first block of code works, however, the second does not. The only difference is that I have created a variable and used it in a function. Can someone explain why this does not work?
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p id="demo">My First Paragraph.</p><input type="button" onclick="change()" value="Click Me!">
<script>
function change() {
document.getElementById("demo").innerHTML = "Paragraph changed.";
};
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p id="demo">My First Paragraph.</p><input type="button" onclick="change()" value="Click Me!">
<script>
var changeName = document.getElementById("demo").innerHTML;
function change() {
changeName = "Paragraph changed.";
};
</script>
</body>
</html>
2 Answers
Dave McFarland
Treehouse TeacherThis line of code:
var changeName = document.getElementById("demo").innerHTML;
Grabs the current HTML that's inside the element with an ID of demo. In other words, it grabs a string of HTML and puts it into the variable changeName.
This function:
function change() {
changeName = "Paragraph changed.";
};
just changes the value of the changeName variable to "Paragraph changed." but doesn't update the page.
Mikis Woodwinter's answer above is correct.
var changeName = document.getElementById("demo");
This code creates what's called a "reference" to the proper DOM element and stores that into changeName -- in other words changeName acts like a pointer to the real DOM node on the page.
Technically document.getElementById() returns an object -- the DOM element -- and with that object comes various DOM element properties like innerHTML which you can change. innerHTML itself is just a property of an object and because of that, you can't create a reference to it using the technique you tried.
Hope that helps a little.
miikis
44,957 PointsI think the second one's not working because the variable changeName is grabbing the element with id:demo's HTML node and for some reason??, that I am not able to elucidate at the moment, that is a no-no. This would work though:
<script>
var changeName = document.getElementById("demo");
function change() {
changeName.innerHTML = "Paragraph changed.";
};
</script>