@erlynascarate
Posted
Hello, nice work on the project!
You could also do this:
let view = ''
data.forEach((item) => {
----scoreArr.push(item.score)
----const div = `
--------<div class="${item.category.toLocaleLowerCase()} summary__item ">
------------<div class="${item.category.toLocaleLowerCase()}__description summary__description">
----------------<img src="${item.icon}" alt="${item.category} icon" />
----------------<h3>${item.category}</h3>
------------</div>
------------<div class="summary__scores">
----------------<span>${item.score}</span>/
----------------<span>100</span>
------------</div>
--------</div>
----`
----view += div
})
summaryContent.innerHTML = view
Instead of this:
data.forEach((item) => {
----// ... (HTML generation)
----summaryContent.innerHTML += div
})
And here's why
In the first snippet:
let view = ''
data.forEach((item) => {
----// ... (HTML generation)
----view += div
})
summaryContent.innerHTML = view
The code creates an empty view
string and iterates over the data
array, generating the HTML content for each item
and appending it to the view
string using string concatenation. Finally, after the loop, the entire view
string is set as the innerHTML
of the summaryContent
element. This means that the entire HTML content is built in memory before being added to the DOM.
In the second snippet:
data.forEach((item) => {
----// ... (HTML generation)
----summaryContent.innerHTML += div
})
The code directly appends the generated HTML content to the summaryContent
element using innerHTML
. In this case, the HTML content is added to the DOM at each iteration of the loop. This approach can be less efficient because the DOM is modified multiple times, and each modification can trigger reflows and repaints.
In general, the first approach with the view
string can be more efficient because it reduces the number of DOM modifications. Building the entire HTML content in memory and then setting it once as the innerHTML
of the target element is generally faster than appending individual elements one by one.
However, if the data
array is relatively small, the performance difference between the two approaches might not be significant. In such cases, you can choose the approach that you find more readable and maintainable. The first approach with the view
string might be considered more organized, as it separates the HTML generation from DOM manipulation.
Marked as helpful
@alibeniaminali
Posted
@erlynascarate
Thank you for explaining and giving me a better solution. I already applied the feedback from you.
Kind regards, Ali