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 JavaScript Basics (Retired) Working With Numbers The Mad Libs Challenge Revisited

melissa brown
melissa brown
4,670 Points

what is the best way to add the js to the html elements?

for example do we add the h2 brackets like he has done in this code. if we have multiple sections for different html elements and css layout then is it best practice to add their location eg p, h2 in the jscript? what about when you start adding div etc then would we have to break up our js and add the src script into the html? what is the best practice so it doesnt get messy?

Roger Nordqvist
Roger Nordqvist
7,007 Points

If you start to get a lot of DOM manipluation I would suggest that you start looking into Angular.js from google. I believe that is the most structured and easy way to handle it with.

2 Answers

Vance Rivera
Vance Rivera
18,322 Points

First and most importantly you will always want your js file added as the last to your body element. This way all of your Dom elements have been loaded and your js script has access to manipulate the Dom elements. Unless you are writing some arbitrary scripts you will want to stay away from writing script tags within your HTML tags as a placement. I never found a good reason to add a script tag within HTML tags as a placeholder. In order to manipulate the Dom and in your case insert text or other dynamic HTML markup you would want to use the concept of traversing the dom. Traversing is basically a way to navigate through the HTML elements based on their relations to other elements. With traversing you will use element selectors as well as CSS classes, id's, data tags, and other attributes to target specific elements. However before you can run you have to crawl so it will probably suite you best to work through the basic. I promise by the time you get through jquery you will be on your way manipulating the Dom the way you want. Hope this helps.

kenneth cootauco
kenneth cootauco
1,553 Points

Hi Melissa,

Other Javascript courses here will go through exactly what you're looking for. Just briefly, in the DOM, there are ways to target other elements in the HTML and directly insert text/html. I find that using classes and/or ids in each element is the easiest (and cleanest) way to do this.