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:

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:

About Jay Versluis

Jay is a medical miracle known as a Super Survivor. He runs two YouTube channels, five websites and several podcast feeds. To see what else he's up to, and to support him on his mission to make the world a better place, check out his Patreon Campaign.

Add your voice!