In this article, we will look at 4 jQuery techniques that can be used to create an HTML element, and we will be testing out the code for the creation of an element by different methods.
Approach: One of the easier ways is to just use $ (‘<div></div>’) which is great for readability but technically the piece of code will create an <div> element, but it will not add it to your HTML DOM. You need to use some other methods like append(), prepend(), etc.
It is recommended to run and test the code below and check out the fastest technique for creating an element, as the time taken by the code varies depending upon the web browser.
For the below code, you must incorporate jQuery into your code. One of the easiest ways to do this is to just copy and paste the jQuery CDN into your HTML header tag.
CDN link used:
Method 1: In the following example, the document.createElement() method creates the HTML “div” element node. The date.getTime() method is used to return the number of milliseconds since 1 January 1970. Run the code below to find out its performance.
Conclusion: The $(document.createElement(‘div’)); is the fastest method, even the benchmarking supports, this is the fastest technique to create an HTML element using jQuery.
Reason: It is because jQuery doesn’t have to identify it as an element and create the element itself.
Alternate way: Using just document.createElement(‘div’) without jQuery will increase the efficiency a lot and will also append the element to DOM automatically.