Recently I've been doing a lot of modal window pop-ups and what not, for which I used jQuery. The method that I used to create the new elements on the page has overwhelmingly been along the lines of:
$("<div></div>");
However, I'm getting the feeling that this isn't the best or the most efficient method of doing this. What is the best way to create elements in jQuery from a performance perspective?
This answer has the benchmarks to the suggestions below.
jQuery html() Method The html() method sets or returns the content (innerHTML) of the selected elements. When this method is used to return content, it returns the content of the FIRST matched element. When this method is used to set content, it overwrites the content of ALL matched elements.
jQuery is a lightweight, "write less, do more", JavaScript library. The purpose of jQuery is to make it much easier to use JavaScript on your website. jQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish, and wraps them into methods that you can call with a single line of code.
I use $(document.createElement('div'));
Benchmarking shows this technique is the fastest. I speculate this is because jQuery doesn't have to identify it as an element and create the element itself.
You should really run benchmarks with different Javascript engines and weigh your audience with the results. Make a decision from there.
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