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 trialfurkan2
Courses Plus Student 3,044 PointsObjects 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>
</form>
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
231,261 PointsIt 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;