Friday, March 22, 2013

Modifying the DOM Using jQuery


JQuery also lets you insert, append, remove, and replace elements from the HTML DOM so you can modify the document structure. For example, suppose you’re calling a remote service from client-side jQuery code and, based on what the service returns, you need to generate HTML markup on the fly. Such tasks can be accomplished using jQuery methods that let you manipulate the HTML DOM.

after()  - Inserts content after a specific element
append()  - Appends content as specified by the parameter to the end of the matched elements.
appendTo()  -  Appends the matched elements to the end of a target element.
attr()  -  Gets or sets an attribute value
before()  -  Inserts content before a specific element
clone()  -  Makes a deep copy of an element and its contents
empty()  -  Removes all the child nodes of a specific element
html()  -  Returns the HTML markup of an element
insertAfter()  -  Inserts content after a specific element
insertBefore()  -  Inserts content before a specific element
prepend()  -  Inserts content as specified by the parameter at the beginning of the matched elements
prependTo()  -  Inserts the matched elements at the beginning of a target element
remove()  -  Removes a specific element and all its child elements
removeAttr()  -  Removes an attribute from an element
replaceWith()  -  Replaces target element with specific content
text()  -  Returns the text content of an element including all child elements
val()  -  Returns the value from a form element
wrap()  -  Wraps every element of a matched set in a given element

Some Examples:
$("#container").append("<div>Hello</div>");
$("<div>Hello</div>").appendTo("#container");
$("span").replaceWith("<div class='class1'>Hello Universe!</div>");
$("<div class='class2'>Hello World!</div>").replaceAll("div.class1");

The first line of code from Listing adds <div>Hello</div> at the end of the container element. So, if the container is a <span> element, then after calling the append() method, the effective markup is <span id='container'><div>Hello</div></span>.

The second line of code uses the appendTo() method. This method is similar to the append() method with one difference: append() is invoked on the target element and accepts markup to be appended. The appendTo() method accepts a target element as a parameter and appends the specified markup at the end of the target.

The example of the replaceWith() method replaces all the <span> elements with <div class='class1'> elements. For example, if the original markup is <span>Hello World!</span>, then after calling the replaceWith() method, the new markup is <div class='class1'>Hello Universe!</div>.

Finally, the replaceAll() method replaces all the <div> elements with the CSS class class1 with <div>Hello World!</div>.

No comments:
Write comments
Recommended Posts × +