jQuery 3 - Creating & Modifying The DOM
Written by Ian Elliot   
Monday, 31 October 2016
Article Index
jQuery 3 - Creating & Modifying The DOM
Move and Copy
Inserting, Replacing & Removing
Building a Dynamic Table

jQuery provides you with methods for working with the DOM in ways powerful enough to allow you to create complete pages or custom controls that extend what you can incorporate into an HTML page. You aren't just limited to changing what is already there, you can create it from scratch.   

 Available as a Book:

smallcoverjQuery

buy from Amazon

  1. Understanding jQuery
  2. Basic jQuery CSS Selectors
       Extract: The DOM
  3. More Selectors
       Extract: Basic Selectors
  4. The JQuery Object
  5. Filters 
  6. DOM Traversal Filters 
  7. Modifying DOM Objects
       Extract: Modifying The DOM 
  8. Creating Objects & Modifying The DOM Hierarchy
  9. Working With Data
       Extract: Data ***NEW!!!
  10. Forms 
  11. Function Queues
  12. Animation 
  13. jQuery UI
  14. jQuery UI Custom Control
  15. Easy Plugins 
  16. Testing With QUnit
  17. Epilog A Bonus Function

Also Available:

jquery2cover

buy from Amazon

 

When you first start working with jQuery there is a tendency to focus on the selector. Writing a selector that picks out the exact elements in the page that you are looking for can be a challenge. However, you really shouldn't get too bogged down in the details.

You can use jQuery to find elements and then modify them, but in many cases it is as useful, and probably more useful, to use jQuery to create elements for you. Think of HTML as a markup language for jQuery and always remember that you don't actually have to use it. 

For example, it is easy to write a function that will dynamically create a table, complete with data, if this is what is required. You can also use the same techniques to build custom controls using nothing but the basic DOM elements. 

We have two tasks to examine. The first is how do you create a DOM object and the second is how do you modify the existing DOM by inserting, replacing and delete DOM objects?

Making DOM Objects

jQuery makes it trivial to create a DOM object, wrapped as a jQuery object.

All you have to do is use the global jQuery function. For example, to create a div you simply use:

var divObj=$("<div>");

Notice that you do need to include the full tag including "<>". The command $("div") is a selector that returns a jQuery object containing an array of all of the div elements in the page.

The rule is that if you make the call $(string) then, if the string parses to valid HTML, the elements it contains are created as a DOM sub-tree - more of this later. If the string isn't valid HTML, then jQuery attempts to interpret it as a selector and to return the corresponding elements as an array in a jQuery object.

This is very convenient but notice that it is something that can create hard to find errors if you don't keep in mind the difference between $("p") and $("<p>")

You also need to notice that to create a single DOM object you don't need a closing tag to make the HTML valid. That is, you don't have to use:

var divObj=$("<div></div>");

It works but the closing tag is unnecessary.

The final thing to notice is that the object that is created is a jQuery object containing an array of DOM element objects, even when only one DOM object has been created.

That is:

var divObj=$("<div>")[0];

is a DOM element object and not a jQuery object.

When you are creating a single HTML element object the closing tag doesn't matter, but when you are working with multiple objects it becomes vital.

If you specify more than one HTML tag then how you specify the closing tag determines how the objects are nested.

If you just write one tag after another without specifying any closing tags then each object is created as a child of the one before.

For example:

var divObj=$("<div><div><p>");

creates a single object which corresponds to the sub-tree:

<div>
  <div>
   <p>
  
</p>
 
</div>
</div>

You can create other arrangements of sub-tree by explicitly including the closing tags.

For example:

var divObj=$("<div></div><div></div><p></p>");

creates an array of three DOM objects. For example:

divObj[0];

is an object corresponding to he first div.

The rule is that the valid HTML is parsed to create a single object for each element at the top level with other objects nested within it as the markup dictates. 

Inserting New Elements

Now that we can create new DOM structures we need to find ways to insert this into the existing DOM. There are three distinct possibilities:

  • insert as child
    If you have located an element then you could insert the new element as a child i.e. inside the tag of the existing element. 
  • insert as parent
    You could insert the new element as the parent of the existing element i.e. surround the existing element's tag by the new element's tag
  • insert as sibling
    Finally you could insert the new element before or after the existing element i.e. not within it or surrounding it. 

Let's take a look at how jQuery achieves each of these actions.

Adding to the DOM As A Child Element

At the moment we are creating jQuery DOM objects and even DOM sub-trees, but so far we haven't added them to the page's DOM. What this means is that the new elements don't actually appear on the page and, as a general pattern, it is worth building the DOM sub-tree of elements you need and then add it to the DOM in one operation.

Of course, where you add it to the page's DOM controls where the new element will appear. As the DOM forms a tree structure of elements, what you have to do is use jQuery to select a particular node in the tree and then use the append or appendTo methods to add the new sub-tree of elements.

The only difference between the two methods is the order.

The append method:

element1.append(element2);

will append element2 as the last child of element1 and return element1.

The appendTo method:

element1.appendTo(element2);

appends element1 as the last child of element2 and returns element1.

For example:

$("body").append(divObj);

appends divObj as the last child of the body element and

divObj.appendTo($("body"));

does the same thing.

Which you use is a matter of choice, but notice that append makes it easy to chain methods that modify the object being appended to.

For example:

$("body").append(divObj1).append(divObj2);

appends divObj1 and then divObj2 to the body element .

By contrast the appendTo method makes it easy to chain methods that work on the object being appended.

For example:

divObj.appendTo($("body")).attr("id","myDiv");

appends the divObj to the body element and sets the divObj's id to myDiv.

As well as append and appendTo there is also prepend and prependTo which work in the same way but add the new element as the first child.

As a short cut you can also use append/prepend with a string of valid HTML which creates first creates the DOM subtree and then adds it. So, for example:

$("body").append("<div>");

adds a new div object to be the last child of the body element.

You can also add a raw DOM element object using append/prepend without having to wrap it in a jQuery object first.

For example after.

var divObj=$("<div></div><div></div><p></p>");

divObj[0] is a raw DOM element object and you might think that you need to use:

$("body").append($(divObj[0]));

but you can use:

$("body").append(divObj[0]);

 

justjquery



Last Updated ( Wednesday, 30 November 2016 )