Creating, Operating on, and Inserting DOM Elements - J Query

Problem
You want to create new DOM elements (or a single element) that are immediately selected, operated on, and then injected into the DOM.

Solution

If you haven’t figured it out yet, the jQuery function is multifaceted in that this one function performs differently depending upon the makeup of the parameter(s) you send it. If you provide the function with a text string of raw HTML, it will create these elements for you on the fly. For example, the following statement will create an <a>element wrapped inside of a <p>element with a text node encapsulated inside of the
<p>and <a>elements:

Now, with an element created, you can use jQuery methods to further operate on the elements you just created. It’s as if you had selected the <p>element from the get-go in an existing HTML document. For example, we could operate on the <a>by using the .find() method to select the <a>element and then set one of its attributes. In the case of the following code, we are setting the hrefattribute with a value of http://www.jquery.com:

This is great, right? Well, it’s about to get better because all we have done so far is create elements on the fly and manipulate those elements in code. We have yet to actually change the currently loaded DOM, so to speak. To do this, we’ll have to use the manipulation methods provided by jQuery. The following is our code in the context of an HTML document. Here we are creating elements, operating on those elements, and then inserting those elements into the DOM using the appendTo() manipulation method:

Notice how I am using the end() method here to undo the find() method so that when I call the appendTo() method, it appends what was originally contained in the initial wrapper set.

Discussion

In this recipe we’ve passed the jQuery function a string of raw HTML that is taken and used to create DOM elements on the fly. It’s also possible to simply pass the jQueryfunction a DOM object created by the DOM method createElement():

Of course, this could be rather laborious depending upon the specifics of the usage when a string of HTML containing multiple elements will work just fine.
It’s also worth mentioning here that we’ve only scratched the surface of the manipulation methods by using the appendTo() method. In addition to the appendTo() method, there are also the following manipulation methods:

  • append()

  • prepend()

  • prependTo()

  • after()

  • before()

  • insertAfter()

  • insertBefore()

  • wrap()

  • wrapAll()

  • wrapInner()


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

J Query Topics