Just jQuery The Core UI - Creating Objects |
Written by Ian Elliot | |||||||
Thursday, 29 December 2022 | |||||||
Page 2 of 6
Inserting New ElementsNow that we can create new DOM structures we need to find ways to insert this into the existing DOM. There are three distinct possibilities:
Let's take a look at how jQuery achieves each of these actions. Adding to the DOM as a Child ElementAt 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. As a general pattern, it is worth building the DOM sub-tree of elements you need and then adding it to the DOM in one operation. Of course, where you add it to the page's DOM determines 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); appends element2 as the last child of element1 and returns element1. That is, element2 is the new object in the DOM. The appendTo method: element1.appendTo(element2); appends element1 as the last child of element2 and returns element1. That is, element1 is the new object in the DOM.
$("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 its id to myDiv. As well as append and appendTo there are also prepend and prependTo which work in the same way but add the new element as the first child rather then the last. As a shortcut, you can also use append/prepend with a string of valid HTML which 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]); |
|||||||
Last Updated ( Thursday, 29 December 2022 ) |