In this tutorial, a will show you how to Manipulate DOM (Document Object Model) using jQuery. You will learn how to use the basic and common jQuery APIs or methods. The tutorial aims to provide the students and new programmers a reference for learning how they can give their better experience for your using their developed web application using DOM Manipulations. Here, snippets and sample source codes are provided to give you more understanding of the scripts.
DOM stands for Document Object Model. It is a cross-platform and language-dependent interface. It treats an XML or HTML document as a tree-structured with each node representing a different part of the document.
DOM Manipulation is a process in web development in which you can add, create, and edit the document nodes to make your web applications more creative and easy to use. Manipulating DOM in your web application can result in a better experience for your end-users.
Here are some of the basic methods or APIs of the jQuery Library for manipulating the document nodes.
The Append API allows you to insert text, element, or node inside a specific parent element or node. The appended element will be added after the last child of the selected parent node. Here's an example of usage in jQuery.
$('body').append(`<div>Hello World!</div>`)
The Prepend API allows you to insert text, element, or node inside a specific parent element or node. The prepend element will be added before the first child of the selected parent node. Here's an example of usage in jQuery.
$('div#firstChild').prepend(`<div>Hello World!</div>`)
The Hide API allows you to hide the visible node on the interface.
$('div#firstChild').hide()
The Show API allows you to show the hidden node on the interface.
$('div#firstChild').show()
The Before API insert new element or nodes like Prepend API. The difference between the 2 API is Before API insert the element before the selected document node.
$('div#SecondChild').before(`<h1>Second Child</h1>`)
The After API insert new element or nodes like Append API. The difference between the 2 API is After API insert the element after the selected document node.
$('div#SecondChild').after(`<h1>Third Child</h1>`)
The Attribute API gets the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.
// Getting the the attribute value for the matched element var redirect = $('a#AnchorElement').attr('href'); // Setting the the attribute value for the matched element $('a#AnchorElement').attr('href', 'https://myapp.com/home');
The Add Class API allows you to add class value to the matched elements or nodes.
$('a#AnchorElement').addClass('text-color-change');
The Remove API allows you to remove the set of matched elements or nodes of the document.
$('a#AnchorElement').remove();
The above APIs are just some of the methods for Manipulating DOM in web development.
Here's an example program or web application that demonstrates the listed jQuery APIs functionality in web development.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script> <style> html, body{ min-height:100%; width:100%; } </style> </head> <body> <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient"> <div class="container"> <div> </div> </div> </nav> <div class="container-fluid px-5 my-3"> <!-- Item List Container --> <div class="col-lg-6 col-md-8 col-sm-12 mx-auto list-group mb-3" id="item-lists"> </div> <!-- End of List Container --> <!-- Main Button Container --> <div class="col-lg-6 col-md-8 col-sm-12 mx-auto text-center"> </div> <!-- Main Button Container --> </div> </body> </html>
// Generate Random Key function random_key(){ var key = Math.random().toString(36).slice(2); while(true){ if($(`#${key}`).length > 0){ key = Math.random().toString(36).slice(2); }else{ return key; } } } // Creating and new DOM function new_dom(){ var dom_id = random_key(); var new_el = $('<div>') new_el.attr('id', dom_id) new_el.addClass('list-group-item') new_el.append(`<h3>Example DOM #${dom_id}</h3>`) new_el.append(`<hr>`) new_el.append(buttons()) return new_el; } // Creating action buttons function buttons(){ var new_el = $('<div>') new_el.addClass('text-center') new_el.append(`<button class="btn btn-sm btn-outline-primary rounded-0 mx-1" onclick="add_before(this)" type="button">Add Before This</button>`) new_el.append(`<button class="btn btn-sm btn-outline-info rounded-0 mx-1" onclick="add_after(this)" type="button">Add After This</button>`) new_el.append(`<button class="btn btn-sm btn-outline-success rounded-0 mx-1" onclick="regenerate_text(this)" type="button">Generate New Content</button>`) new_el.append(`<button class="btn btn-sm btn-outline-danger rounded-0 mx-1" onclick="remove_item(this)" type="button">Remove this Item</button>`) return new_el; } // Add New DOM $('#add_new').click(function(){ var new_el = new_dom(); $('#item-lists').append(new_el) }) /** * Adding an Element before the specific Element * this = the element of the button * */ function add_before($this){ //converting JS element to jQuery DOM $this = $($this) // Getting the Parent DOM var _parent = $this.closest('.list-group-item') //Generate New DOM var new_el = new_dom(); new_el.hide() // Adding new element before the parent DOM _parent.before(new_el) //Animate element for showing new_el.show('slideDown') } /** * Adding an Element after the specific Element * this = the element of the button * */ function add_after($this){ //converting JS element to jQuery DOM $this = $($this) // Getting the Parent DOM var _parent = $this.closest('.list-group-item') //Generate New DOM var new_el = new_dom(); new_el.hide() // Adding new element after the parent DOM _parent.after(new_el) //Animate element for showing new_el.show('slideDown') } /** * generating new Text of an Element * this = the element of the button * */ function regenerate_text($this){ //converting JS element to jQuery DOM $this = $($this) // Getting the Parent DOM var _parent = $this.closest('.list-group-item') // getting the DOM of the element that holds the text var h3 = _parent.find('h3') var new_key = random_key(); h3.text(`Example New Generated Key #${new_key}`); } /** * Removing the Parent Element * this = the element of the button * */ function remove_item($this){ //converting JS element to jQuery DOM $this = $($this) // Getting the Parent DOM var _parent = $this.closest('.list-group-item') // Removing the DOM _parent.remove() }
Here's the snapshot of the result of the given source code of the sample web application.
I also provided the zip file for the source code I have shared above. You can download it for free by clicking the download button below this tutorial article.
That's the end of this tutorial. I hope this DOM Manipulation tutorial helps you with what you are looking for and add up to your knowledge for enhancing your programming skills using JavaScript and jQuery Library.