Skip to content
Fix Code Error

jQuery document.createElement equivalent?

March 13, 2021 by Code Error
Posted By: Rob Stevenson-Leggett

I’m refactoring some old JavaScript code and there’s a lot of DOM manipulation going on.

var d = document;
var odv = d.createElement("div");
odv.style.display = "none";
this.OuterDiv = odv;

var t = d.createElement("table");
t.cellSpacing = 0;
t.className = "text";
odv.appendChild(t);

I would like to know if there is a better way to do this using jQuery. I’ve been experimenting with:

var odv = $.create("div");
$.append(odv);
// And many more

But I’m not sure if this is any better.

Solution

Here’s your example in the “one” line.

this.$OuterDiv = $('<div></div>')
    .hide()
    .append($('<table></table>')
        .attr({ cellSpacing : 0 })
        .addClass("text")
    )
;

Update: I thought I’d update this post since it still gets quite a bit of traffic. In the comments below there’s some discussion about $("<div>") vs $("<div></div>") vs $(document.createElement('div')) as a way of creating new elements, and which is “best”.

I put together a small benchmark, and here are roughly the results of repeating the above options 100,000 times:

jQuery 1.4, 1.5, 1.6

               Chrome 11  Firefox 4   IE9
<div>            440ms      640ms    460ms
<div></div>      420ms      650ms    480ms
createElement    100ms      180ms    300ms

jQuery 1.3

                Chrome 11
<div>             770ms
<div></div>      3800ms
createElement     100ms

jQuery 1.2

                Chrome 11
<div>            3500ms
<div></div>      3500ms
createElement     100ms

I think it’s no big surprise, but document.createElement is the fastest method. Of course, before you go off and start refactoring your entire codebase, remember that the differences we’re talking about here (in all but the archaic versions of jQuery) equate to about an extra 3 milliseconds per thousand elements.


Update 2

Updated for jQuery 1.7.2 and put the benchmark on JSBen.ch which is probably a bit more scientific than my primitive benchmarks, plus it can be crowdsourced now!

http://jsben.ch/#/ARUtz

Answered By: nickf

Related Articles

  • how to use canvas in JavaScript flappy bird code
  • Active tab issue on page load HTML
  • TailwindCSS in Next.JS not rendering properly in Webkit
  • Is it possible to apply CSS to half of a character?
  • insert tables in dataframe with years from 2000 to…
  • Sort table rows In Bootstrap
  • How can I resolve Web Component Testing error?
  • Pandas pivot_table: filter on aggregate function
  • setTimeout function not working : javascript
  • state data can not be set using useState in reactjs
  • d3.js - draw arrow line from border to border
  • How to add fade animation for this tab
  • "Thinking in AngularJS" if I have a jQuery background?
  • In C# how can I access a variable outside of the…
  • Only one element is appended in the div
  • D3.js: Update barplot based on variable input
  • SQL find sum of entries by date including previous date
  • python 3.2 UnicodeEncodeError: 'charmap' codec can't…
  • Bootstrap modal in React.js
  • How do i update a javascript variable as its value changes?
  • Show/hide 'div' using JavaScript
  • How to create a game over screen for a basic HTML/JS game?
  • How do I close my Modal using the react-modal component?
  • React Multi-level push menu SCSS Back button not working
  • What does AngularJS do better than jQuery?
  • Having trouble with my nav bar/header, It used to…
  • How to use html template with vue.js
  • Jquery fadeToggle Trouble
  • jQuery Mobile: document ready vs. page events
  • getting text input from a form in react.js using Refs
  • How do I keep only the first map and when the game…
  • Troubleshooting "Warning: session_start(): Cannot…
  • $ is not a function - jQuery error
  • How do I append a node to an existing XML file in java
  • How do you easily create empty matrices javascript?
  • I need to sum values with specific condition
  • My submit button is not getting enabled . How do i do that?
  • How can we load color from a sequential scale into a…
  • d3.js - dragmove circle with v6 not work as expected
  • NEXT.JS with persist redux showing unexpected behaviour
  • Javascript validate all checkboxes are selected
  • Add calculated column to df2 for every row entry in…
  • Azure Sql : Unable to Replace HTML String
  • Obtain most recent value for based on index in a…
  • What are the undocumented features and limitations…
  • Onclick event not happening when slick slider is…
  • How do i use bootstrap and custom css i.e.…
  • Cannot make table responsive
  • Linking of Page on same page with nextjs
  • What does this symbol mean in JavaScript?
  • When clicked, hide others and so on [Code optimisation]
  • Polymer 1.0 Trying to make a splitter which works…
  • What is your most productive shortcut with Vim?
  • Uncaught syntaxerror: unexpected identifier?
  • Next.js prerendering error on getStaticPaths
  • How to use Servlets and Ajax?
  • react-table has a issue with rendering in next.js
  • navbar functionlity in react and tailwind is really…
  • Why is Ember throwing "Uncaught Error: Assertion…
  • Dynamically injecting a template in Polymer 1.0
  • How to read and write xml files?
  • data.table vs dplyr: can one do something well the…
  • AppCompat v7 r21 returning error in values.xml?
  • Reset/remove CSS styles for element only
  • Dynamic creation of table with DOM
  • Why doesnt my table sort my div variable in numerical order?
  • How do I expand the output display to see more…
  • JavaScript TypeError: Cannot read property 'style' of null
  • Pandas / Python - Compare numerically each row with…
  • React router - click on card and redirect to a new…
  • How to use 2 columns as "key" to get MAX value of…
  • Smart way to truncate long strings
  • html tables & inline styles
  • How do you parse and process HTML/XML in PHP?
  • select unique rows based on single distinct column
  • backbone view events don't work after re-render
  • Create table using Javascript
  • How can I get the correct ID assigned to the delete function
  • Highlight a word with jQuery
  • .prop() vs .attr()
  • Ember data createRecord not working: "TypeError:…
  • Next JS build isn't building out every path
  • Moving average in MYSQL without dates but grouped by…
  • How do I properly deprecate Gutenberg block
  • How do I include a JavaScript file in another…
  • does Backbone.Models this.get() copy an entire array…
  • HTML Canvas Full Screen
  • Hide one dropdown in side menu when another opens
  • Append distributed child to element in Polymer
  • Cannot update nested dictionary properly
  • Error in styles_base.xml file - android app - No…
  • Using setInterval for creating animation
  • Oracle sql query to group two sets of dates if sequencials
  • How to apply rolling t.test with pandas?
  • Python Monthly Change Calculation (Pandas)
  • d3.js - Force simulation drag does not move with the mouse
  • Make only one post request with new state after…
  • I am getting TypeError: Cannot read property 'push'…
  • D3 chart integration into Vuejs
  • Getting a "TypeError" when trying to validate a form

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How and when to use ‘async’ and ‘await’

Next Post:

Convert a String representation of a Dictionary to a dictionary?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error