I’m just wondering how i could make this code more efficient. I feel like there is a lot of code here to accomplish a simple task. But i’m not sure how to better it? Is there a way to dynamically create divs? Or is tehre a way to reduce the number of “getElementById” calls i make?
Share
There are a number of improvements you might make, whether it’s in terms of speed, readability, or maintainability. Here’s a list of some off the top of my head:
Cache the note element in a variable if you’re going to reuse it. This makes your code faster since you don’t have to grab the element again to use it.
Instead of repeating your code so much, you could iterate over something that keeps track of your notes. In this example I am using an array of ids and an object containing the ids and notes as property-value pairs.
The
boxelement can be cached as well through a global variable. Might not be good style, but this should be faster than getting it from the DOM each time.Putting everything together, you have the following:
It might even be better to keep your
notesarray instead of using thenotesobject I have above, as long as you make sure the order is the same as thenoteDivsarray. It will be faster, but also slightly more work to maintain. You would also need to have onedivfor each element innotes, which you currently don’t have.