Take the 2-minute tour ×

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:

  1. Use replace()
  2. remove() the first element and add() the second element
  3. hide() the first element and show() the second element

What is the performance differences between:

  • 1 vs. 2
  • 2 vs. 3
  • 1 vs. 3

Are there additional performance considerations if the elements are of different types? Or if the elements are buttons or form fields?

share|improve this question
I'd say it depends on how and where you generate your markup (i.e. how flexible you need to be) as for example you'd have to generate content JS-side when you are using replace/remove/add. If you are really interested in performance you can easily test your cases here: jsperf.com –  m90 Sep 18 '11 at 9:58
add comment

2 Answers

up vote 5 down vote accepted

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.

share|improve this answer
Thanks for the note about the reflow. –  Ahmad Alfy Sep 18 '11 at 10:01
Thank you @Alex! For readers interested in more information (in addition to your link), I found another descriptive article worth sharing from the Opera team –  jp_hill Sep 18 '11 at 20:27
add comment

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.

share|improve this answer
add comment

Your Answer


