Rob's Blog - October 2009

Contents

Here are Rob's Blog entries for October 2009.

Blog entries for other months can be found in the main blog index.

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

UPDATE: Whilst this remains an interesting example of creating a simple plugin, I no longer recommend this way of creating elements in jQuery. Instead just pass the html you want to use into jQuery directly as a string, e.g. var myH1Element = jQuery("<h1>My H1 Test</h1>");.

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
Modified: 2011-06-30 07:19:00