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
dylan kane
2,772 PointsHow do you get the text value of an h1 by clicking an html button?
How can I set a javascript variable to the text value in a specific h1 by clicking a button?
I tried doing it with this code:
Html:
<h2 id="gameTitle">Hello</h2> <button onclick=”getElementText("gameTitle")”class=”newLobby”>Create Lobby</button>
JS:
function getElementText(elementID){ var elementText = document.getElementById(elementID).innerHTML; console.log(elementText); }
but I get this error: Uncaught SyntaxError: Unexpected token }
1 Answer
Steven Parker
243,656 PointsYour JavaScript looks good, but in your HTML you have nested quotes where you establish the onclick handler. When nesting quotes, the inner ones must be escaped or you must use a different type of quote. Here's what it would look like using single quotes (apostrophes) for the inner set:
<h2 id="gameTitle">Hello</h2>
<button onclick="getElementText('gameTitle')" class=”newLobby”>Create Lobby</button>
It works fine after that change.
dylan kane
2,772 Pointsdylan kane
2,772 Pointsthanks so much