I'm doing The Odin Project and my current project involves adding elements to the HTML using JS. The webpage should be tabbed with each tab being drawn using a separate JS module. In the instructions here, they say
Each module will export a function that creates a div element, adds the appropriate content and styles to that element and then appends it to the DOM.
As I worked through the project, I felt that I could instead create the elements in the module and have the module export the elements themselves (instead of a function) which are then appended in the main script.
My approach (simplified):
// menu.js const menu = document.createElement('div'); /* add children to menu */ export default menu;
// index.js import menu from './menu.js' const content = document.querySelector('#content') content.appendChild(menu)
Compared to the suggestion in the project, what are the advantages and disadvantages of each method?
Also if you use a function as suggested, does that mean that we would need to pass the parent element into the function since its not initialized within the module?
Edit: Also, I could be misinterpreting their suggestion where instead of having the function append the elements to the main content element, I should instead have the function return an element similar to my approach, just enclosed in a function à la functional programming.
Juan Pablo Isaza
In my personal experience it depends on how modular you want the module to be. A menu you may want to have a very similar layout throughout the application. However with something like a modal popup you may want to have the module return a skeleton which you can then populate with an element in your
You also may want to consider how uniform the structure of your modules are if you intend to reuse them or have someone else work the same modules - in this case I'd think it better that most/all the modules behave in a similar fashion.
Personally, my modules have a snippet of html you add to the body of the page(a one liner like a div) and a js import to interact with the module which will use that html div to do what it needs to do.