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 JavaScript and the DOM (Retiring) Getting a Handle on the DOM A Simple Example

Paul Robb
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Paul Robb
Front End Web Development Techdegree Graduate 20,691 Points

What is the preferred way ?

Another way to do this is to add "onclick" to the html and call the function.

------------------------------HTML------------------------------------

<h1 id="myHeading" onclick="changeHeadingColour()">JavaScript and the DOM</h1>

------------------------------Javascript------------------------------------

function changeHeadingColour() { const myHeading = document.getElementById('myHeading'); myHeading.style.color = 'blue';

}

Just wondering if the event listener is the preferred way to do this ?

2 Answers

Steven Parker
Steven Parker
231,236 Points

Using an event listener and keeping all the code in the script is "best practice".

Setting "onclick" in the HTML is more commonly done when there is no separate JavaScript file.