Tuesday, 15 May 2012

jQuery DOM Manipulation

.html() Get the HTML contents of the first element in the set of matched elements
Ex: <div class="demo-box"><b>Demonstration Box</b></div>

$(“div.demo-box").html();  //Output <b>Demonstration Box</b>

.text() Get the HTML contents of the first element in the set of matched elements
Ex: <div class="demo-box"><b>Demonstration Box</b></div>

$(“div.demo-box").text();  //Output Demonstration Box

.val() Get the current value of the first element in the set of matched elements
Ex: <input type=“text” id=“uname” value=“Johnny”/>

$(“uname").val();  //Output Johnny

.append() Insert content, specified by the parameter, to the end of each element in the set of matched elements.

<p>I would like to say: </p>

<script>$("p").append("<strong>Hello</strong>");</script>

Output : <p>I would like to say: <strong>Hello</strong></p>

.prepend() Insert content, specified by the parameter, to the beginning of each element in the set of matched elements.

<p>I would like to say: </p>
<script>$("p").prepend("<strong>Hello</strong>");</script>
Output : <p><strong>Hello</strong> I would like to say:</p>

<div>
                <span>One</span>
                <p>Two</p>
                <span>Three</span>
</div>
.remove() Remove the set of matched elements from the DOM.
$(“div”).remove(“p”);
Output:
<div>
                <span>One</span>
                <span>Three</span>
</div>
.empty() Remove all child nodes of the set of matched elements from the DOM.
$(“div”).empty();
<div>
</div>

<input type=“text” id=“mydata” style=“font-size:10px;”/>

.attr() Get or Set the value of an attribute for the first element in the set of matched elements.
$(“#mydata”).attr(“style”)  // Output : font-size:10px;
$(“#mydata”).attr(“name”,”mynode”) 
// Output : <input type=“text” id=“mydata” name=“mynode” style=“font-size:10px;”/>


 .removeAttr() Remove an attribute from each element in the set of matched elements.
$(“#mydata”).removeAttr(“style”)
//Output : <input type=“text” id=“mydata” />

Dom nodes can be created in Jquery using the $ or jquery()
$(“<div>This is a div element</div>”)
$(“<input></input>”).attr(“type”,”text”).attr(“name”,”mydata”)
The above is equivalent to <input type=“text” name=“mydata”/>
$(“<span><b>Hello world</b></span>”)