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.


Objects to contain variables in - JavaScript

Is it a good idea to create an object in JavaScript to contain variables for all the elements of a particular section of HTML document you are working with, just for the purpose of keeping it clean?

So for example, suppose the following basic HTML code, imagine you are working on a form (i havent added anything semantic just keep it simple):

<form id="user-form">
  <input type="text" id="first-name">
  <input type="text" id="second-name">
  <input type="email" id="email">
  <textarea id="user-text></textarea>
const form_object = {
  first_name: document.getElementById("first-name"),
  second_name: document.getElementById("second-name"),
  email: document.getElementById("email"),
text: document.getElementById("user-text")


1 Answer

Steven Parker
Steven Parker
216,810 Points

It probably depends on what you intend to do with these items, you might not need separate variables defined for each element. And remember, the DOM is already structured so that you can access the contained elements using traversal methods. For example:

const form_object = document.getElementById("user-form");
let first_name = form_object.firstElementChild;