Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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