Adding a DOM element

If you have to modify an existing DOM document in the fly by adding a HTML fragment, you can use the jQuery appendTo() method, that would simplify your job. Being jQuery smart enough to create a jQuery object from a HTML literal fragment, we can even operate on it before appending it.

To add a bottom line to an HTML page, I could write:
var fragment = $('<p><i>Bottom line</i></p>'); // 1
fragment.find('i').attr('class', 'z'); // 2
fragment.appendTo('body'); // 3
1. I create a P element containing an I element, containing some text.
2. Before actually adding it to my document, I can modify it. Here I get the I element and add to it an attribute, class='z'.
3. Finally, I add my fragment at the end of the BODY element.

There is no need of writing this code on three lines, I can squeeze it on just one, but I have to be careful:
$('<p><i>Bottom line</i></p>').find('i').attr('class', 'k').end().appendTo('body');
I need to call end() before appendTo(), otherwise I put to the document only the element returned by find(), and the paragraph would be lost.

No comments:

Post a Comment