Skip to main content

jQuery is a JavaScript library that is not only capable for changing element's content but it can create DOM nodes, too.

In this article, as a part of our jQuery tips ans tricks, jQuery will be used for creating DOM node in runtime.

We're going to use the next HTML code as a sample for adding new element to:

<div id="testdiv">
    jQuery creating DOM node article
</div>

Some of jQuery methods that could be used for creating DOM nodes are:

clone()
append()
appendTo()
before()
insertBefore()
after()
insertAfter()
prepand()
prepandTo()

- Advertisement -
- Advertisement -

For our example we'll use and explain just a couple of them:

prepend()

The function inserts the content at the beginning of the selected element. The content for inserting could be text, a jQuery object or HTML element.

Example for inserting new content at the beginning of the div element

$('#testdiv').prepend('<p>New paragraph</p>');

prependTo()

The function inserts the specified content, but the content for adding has the first place in the syntax (in contrary to the prepend() method)

The following code has the same purpose as the code from above:

$('<p>New paragraph</p>').prependTo('#testdiv');

- Advertisement -