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 trialAndrew Husted
11,271 PointsWhy can't i change h1 inner html using document.getElementsByTagName?
I was messing around with inner.HTML in the console and noticed that I can get and change the inner html of an element when setting variable using document.querySelector('h1'), but not with document.getElementsByTagName('h1'). I was wondering why this is?
1.)
let h1 = document.querySelector('h1')
<undefined
h1.innerHTML
<"Javascipt"
2.)
let h1 = document.getElementsByTagName('h1') I also tried just document.getElementsByTagName('h1')[0]
<undefined
h1.innerHTML
<undefined
4 Answers
Kieran Barker
15,028 PointsThis works for me:
HTML:
<h1></h1>
JavaScript:
const h1 = document.getElementsByTagName('h1')[0];
h1.innerHTML = 'Hello, World!';
zainsra7
3,237 PointsIt's working, after reading your question I tried to test it out too on my editor and it works. Let me show you what I did:
1. Create a simple "test.html" file
<html>
<head></head>
<body>
<h1></h1>
<script src='test.js'></script>
</body>
</html>
2. Create a Javascript file , "test.js" and place it in the same place/folder where html file is present
let h1 = document.getElementsByTagName('h1')[0];
h1.innerHTML = "Hello";
Just run the test.html and you will see the output :)
I hope this answers your question , Happy Coding !
Tim Strand
22,458 PointsBecause .querySelector returns an element (so does getElementById) but getElementsByTagName (note the s) returns a node list (as does querySelectorAll) so you have to access that node list to actually modify the document. So in #2 try h1[0] and it should work.
Andrew Husted
11,271 PointsLike I said in original post I did try specifying index [0]. I also tried ('h1[0]') rather than ('h1')[0], but with no luck. Is my syntax wrong on this?
Andrew Husted
11,271 PointsHmm Yea, it's working for me now too. Must have been a syntax error, thanks for the responses!