jQuery DOM Manipulation

Rumman Ansari   Software Engineer   2023-03-23   132 Share
☰ Table of Contents

Table of Content:


Now you must be familiar with event handling concepts of jQuery. Let us move to another important aspect of jQuery, the DOM manipulation.

jQuery allows you to add, update, read and delete DOM elements. Well, the good aspect is all these functions can be performed with less amount of coding in jQuery.

You will explore the usage of some important DOM manipulating methods in next few cards.


html()

This method is used to read the content of any element in the HTML document and return the text including the markup tags.

Usage: On clicking a button, and alert message "<p>Welcome to <b>jQuery</b> course</p>" will be displayed. Even the markup tages are displayed as it is.


//script
$("button").click(function(){
    alert($("p").html());
});
//HTML
<button>Click me</button>
<p>Welcome to <b>jQuery</b> course!</p>

In case you want only the text, not the markup then use text() method.

These methods can be used not only to read but also to set values to elements.


val()

This method can be used to read form or write to a form element in the webpage.

val() method used without any parameter will read values and the same can be used to write when used with a parameter.

Usage

To read:

On button click, val() will return the value present inside the input tag and display in console


$("button").click(function(){
var s = $("input").val();
console.log(s);
});

To write:

On button click, val() will set the parameter value to input element


$("button").click(function(){
$("input").val("Winter is coming");
});

append()/prepend()

Just like the name states, these are used to add content to the HTML elements.

append() will add the content to the end and prepend() will add content to the beginning.

Usage:

This will add new content at the beginning and end of the <p> element.


//script
$("p").append("<b>new content at end</b>. "); 
$("p").prepend("<b>new content at beginning</b>. ");
 //HTML
<p>Existing text</p>  

remove()

This is used to delete the selected element and all its child element

If you need to delete only the child element then use empty() method.

Usage:

$("#button_1").remove();