I am learning DOM manipulation with jQuery and want to understand browser performance best practices.
Say I have two DOM elements (div, p, ol, etc) and I want a user to only see the first element and then only see the second element.
I could:
What is the performance differences between:
Are there additional performance considerations if the elements are of different types? Or if the elements are buttons or form fields?
Removing and adding elements to the DOM is expensive in terms of resources because of browser reflow, where the browser must re-render part or all of the page. You want to avoid reflows whenever you can; they are costly.
Replacing is essentially a removal then an addition, so the above applies.
Showing and hiding is best, because it is only adding styles to the elements.
The type of elements you're applying these methods too should not lead to a change in the above.
In conclusion, use .show()
and .hide()
for best performance.
Basically if you wan't to hide something and then show it again later, it is always best to hide() and show(). This won't change anything about the dom, just changes the way it is displayed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With