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

James Morrow
James Morrow
1,815 Points

Uncaught TypeError: Cannot call method 'setAttribute' of null

I am receiving this error when I try to execute the following code.

var button = document.getElementById('action'); var input = document.getElementById('text_field');

button.addEventListener('click', function () { console.log('other click'); input.setAttribute('value', 'Hello World'); })

Any help would be appreciated. Thanks!

2 Answers

It's hard to to provide a complete answer without seeing the HTML but based on the error message you are receiving it appears that you are not selecting the correct element when declaring the variable 'input'. If document.getElementById can't find an element with the ID 'text_field' it returns NULL. And you can't run the method 'setAttribute' on a null object.

Check your HTML and make sure the ID of your input element and your call to document.getElementById are the same. Also check that the elements syntax is valid. Once you have these two things resolved your code should work. If things still aren't working, post some HTML.

Ryan

Mozilla document.getElementById Documentation - https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById

JSBIN Working Example - http://jsbin.com/ubahOgUT/1/edit?html,js,console,output