Manipulate the DOM using jQuery

Leave a Comment


jQuery offers a simple and powerful mechanism to manipulate the DOM, or alter properties of the DOM itself or any element.

For example, to alter CSS properties of an element:
$("#helloButton").css("color", "red");
// will turn the color of the button's text to red


In addition to simple manipulations like these, jQuery allows you to create, replace, and remove any markup from a group of elements or the document root with ease.

The following example demonstrates adding a group of elements to an existing <div>:
<div id="myDiv">

</div><script type="text/javascript">
    $("#myDiv").append("<p>I was inserted <i>dynamically</i></p>");
</script>
<p>I was inserted <i>dynamically</i></p>
</div><script type="text/javascript">
$("#myDiv").remove("p"); // will remove the <p> and its children
</script>

This results in:
<div id="myDiv">
  <p>I was inserted <i>dynamically</i></p>
</div>

It is just as easy to remove any element (or a set of elements):
<div id="myDiv">

This code results in:
<div id="myDiv">
</div>

jQuery provides several methods to control the placement of markup :
Method
Description
.prepend()
Inserts at the beginning of the matched element

.before()
Inserts before the matched element

.after()
.after() Inserts after the matched element

.html()
Replaces all the HTML inside the matched element


0 comments:

Post a Comment