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
Corbin Balzan
11,751 PointsEvent Handlers. Console.log won't work. No error messages
What could be causing this problem?
var addButton = document.getElementsByTagName("button");
var addTask = function(){
console.log("Clicked");
}
addButton.onclick = addTask;
<script src="test.js"> </script>
<button id="button"> TestClicker</button>
Corbin Balzan
11,751 PointsPedro,
Thank you for the reply, I looked over the link you inputted and tested the code you attached. It seemed like a valid way to solve the problem, however, I ended up getting the error message "cannot set property of 'onclick' of undefined". Any ideas what could be causing that?
P.S. make sure your response is in the answer section and not under comments so I can give you points :)
Pedro Ferrari
14,295 PointsI sure like this button placement better for replying :P
1 Answer
Pedro Ferrari
14,295 PointsThe script must be loaded after the element is rendered by the page, otherwise it wont return values.
Try moving it around and test it on the developer console, just type "addButton" or "addButton[1]" and see what returns.
You can also type your entire code on the console. Beware that you will lose any changes if you refresh the page tho :)
Pedro Ferrari
14,295 PointsPedro Ferrari
14,295 PointsThat is quite a tricky one, the problem relies on the document.getElementsByTagName.
This method returns a node list, which should be addressed like Arrays. Therefore, to call the function on the button you want to, you must specify an index value, like:
If you wanted to get the function working across all elements on your page, you could do a for loop
For further info: https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName
Hope that helps, cheers!