blog archive contact about feed

Creating A New Element With jQuery, With Or Without A Plugin

One function that seems to be missing in jQuery is to create new elements outside of the current DOM.

There is a good reason for this, normal vanilla JavaScript has the function createElement to do the job for you.

To create a new h1 element for example, we can do the following.

var myH1Element = document.createElement('h1');

We can easily combine this with jQuery to set the text inside for example...

jQuery(myH1Element).text("My H1 Text");

There is one downside, using the standard createElement we're not able to chain functions with jQuery.

The way around this is to wrap the request in jQuery like this...

jQuery(document.createElement("h1"));

Now we can chain this together as before...

jQuery(document.createElement("h1")).text("My H1 Text");

If you don't like the look of that, then we could always create a jQuery plugin, and add a createElement function to jQuery.

jQuery.extend({ createElement : function(elementName) { return jQuery(document.createElement(elementName)); } });

That must be one of the simpliest jQuery plugins ever!

Now we have extended jQuery with a createElement function we can chain calls to it like this.

jQuery.createElement("h1").text("My H1 Text").appendTo("body");

This will create a new h1 element, add the text "My H1 Text" inside the h1, then append the h1 inside the documents body tag.

Entered: 2009-10-19 17:37:26

Rob's Other Blog Entries

See other blog entries for October 2009, or an index of all blog entries.