How to combine DOM elements in jQuery

Sometimes you want to add your own DOM element to an existing class or ID. For example, maybe you’d like to insert something like a header advert into an existing theme without having to hack core files. jQuery makes this possible.

You can either add your own element to the beginning or the end of an existing one by using .prepend() or .append() respectively.

In this example I’m adding my own #myown id inside an existing #header:

// append our #p2HeaderAd to the current #header
var $myOwn = jQuery('#myOwn');
jQuery('#header').append($myOwn);

The first line gets a reference to my own content and stores it inside a variable with the same name. The second line takes this references and appends it as the last element inside the existing #header.

.prepend works the same, but would add my element as the first inside the existing one:

// prepend our #p2HeaderAd to the current #header
var $myOwn = jQuery('#myOwn');
jQuery('#header').prepend($myOwn);




Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or draw on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.