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
nick88p
5,716 PointsDOM manipulation with JS
Good day,
I am trying to change the paragraph content with javascript but keep getting the error "Cannot set property 'innerHTML' of null" even though the element exists, i.e. I am adding the external js just before </body>. Any help would be much appreciated. Thanks!
index.html
<!doctype html>
<html>
<head>
<meta charset= "utf-8">
<title>TEST</title>
</head>
<body>
<p>adfasdf</p>
<script src="index.js"></script>
</body>
</html>
index.js
document.getElementsByTagName("p").innerHTML = "hello";
Nick
3 Answers
Sean Lum
11,949 PointsWhen you are selecting an element in JavaScript with the getElementsByTagName function, it returns an array of elements in a HTMLCollection object. Try doing:
console.log(document.getElementsByTagName("p"));
in your developer tools. You need to select the item in the HTMLCollection in order to update that information. Commonly you can use item(index) on the HTMLCollection, or you can iterate over it in a for loop to find the one you want.
Here is how you can select the first element of the HTMLCollection object and edit the innerHTML: document.getElementsByTagName("p").item(0).innerHTML = "hello";
Here is some documentation on the HTMLCollection object on Mozilla's website: https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection
nick88p
5,716 PointsYes! It's finally working. Thanks a lot. Before posting my question on the forum, I googled possible solutions and what I found was document.getElementsByTagName("p")[0].innerHTML = "hello"; so [0] instead of .item(0) but for some reason [0] did not work for me.
Sean Lum
11,949 PointsSo there is some logic to that. The index will work if the object is an Array object, HTMLCollection is not an Array, it is somewhat different. But like an array, it has a length, which you can use to iterate (for loop) over.
If you are satisfied with the information I have provided, please select best answer on my answer below:
Michelle de Haan-Pitman
2,310 Points@nick88p Not sure why [0] didn't work because [0] and .item(0) should both work. Recommend W3Schools where you can try both out in the browser. Personally I prefer [0].
This aside using [0] in real life makes your code brittle (breakable).
If and when you do the JQuery course you will see that there are much easier and better ways to select and manipulate the DOM.