Basic DOM (Document Object Model) Manipulation using jQuery Tutorial

Introductions

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.

What is DOM?

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.

What is DOM Manipulation?

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.

What are the basic and mostly used jQuery APIs for Manipulating DOM?

Here are some of the basic methods or APIs of the jQuery Library for manipulating the document nodes.

Append API [append()]

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.

  1. $('body').append(`<div>Hello World!</div>`)

Prepend API [prepend()]

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.

  1. $('div#firstChild').prepend(`<div>Hello World!</div>`)

Hide API [hide()]

The Hide API allows you to hide the visible node on the interface.

  1. $('div#firstChild').hide()

Show API [show()]

The Show API allows you to show the hidden node on the interface.

  1. $('div#firstChild').show()

Before API [before()]

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.

  1. $('div#SecondChild').before(`<h1>Second Child</h1>`)

After API [after()]

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.

  1. $('div#SecondChild').after(`<h1>Third Child</h1>`)

Attribute API [attr()]

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.

  1. // Getting the the attribute value for the matched element
  2. var redirect = $('a#AnchorElement').attr('href');
  3.  
  4. // Setting the the attribute value for the matched element
  5. $('a#AnchorElement').attr('href', 'https://myapp.com/home');

Add Class API [addClass()]

The Add Class API allows you to add class value to the matched elements or nodes.

  1. $('a#AnchorElement').addClass('text-color-change');

Remove API [remove()]

The Remove API allows you to remove the set of matched elements or nodes of the document.

  1. $('a#AnchorElement').remove();

The above APIs are just some of the methods for Manipulating DOM in web development.

Example

Here's an example program or web application that demonstrates the listed jQuery APIs functionality in web development.

Interface

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <meta charset="UTF-8">
  4. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Simple DOM Manipulation using JS and jQuery</title>
  7.  
  8. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
  9. <script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
  10. <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>
  11. html, body{
  12. min-height:100%;
  13. width:100%;
  14. }
  15. </style>
  16. </head>
  17. <nav class="navbar navbar-expand-lg navbar-dark bg-primary bg-gradient">
  18. <div class="container">
  19. <a class="navbar-brand" href="./">Simple DOM Manipulation using JS and jQuery</a>
  20. <div>
  21. <a href="https://sourcecodester.com" class="text-light fw-bolder h6 text-decoration-none" target="_blank">SourceCodester</a>
  22. </div>
  23. </div>
  24. </nav>
  25. <div class="container-fluid px-5 my-3">
  26. <!-- Item List Container -->
  27. <div class="col-lg-6 col-md-8 col-sm-12 mx-auto list-group mb-3" id="item-lists">
  28. </div>
  29. <!-- End of List Container -->
  30.  
  31. <!-- Main Button Container -->
  32. <div class="col-lg-6 col-md-8 col-sm-12 mx-auto text-center">
  33. <button class="btn btn-sm btn-primary rounded-pill" id="add_new" type="button">Add New DOM Element</button>
  34. </div>
  35. <!-- Main Button Container -->
  36. </div>
  37. <script src="app.js" ></script>
  38.  
  39. </body>
  40. </html>

JavaScript

  1. // Generate Random Key
  2. function random_key(){
  3. var key = Math.random().toString(36).slice(2);
  4. while(true){
  5. if($(`#${key}`).length > 0){
  6. key = Math.random().toString(36).slice(2);
  7. }else{
  8. return key;
  9. }
  10. }
  11. }
  12.  
  13. // Creating and new DOM
  14. function new_dom(){
  15. var dom_id = random_key();
  16. var new_el = $('<div>')
  17.  
  18. new_el.attr('id', dom_id)
  19. new_el.addClass('list-group-item')
  20. new_el.append(`<h3>Example DOM #${dom_id}</h3>`)
  21. new_el.append(`<hr>`)
  22. new_el.append(buttons())
  23. return new_el;
  24. }
  25.  
  26. // Creating action buttons
  27. function buttons(){
  28. var new_el = $('<div>')
  29. new_el.addClass('text-center')
  30. 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>`)
  31. 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>`)
  32. 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>`)
  33. 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>`)
  34. return new_el;
  35. }
  36.  
  37. // Add New DOM
  38. $('#add_new').click(function(){
  39. var new_el = new_dom();
  40. $('#item-lists').append(new_el)
  41. })
  42.  
  43. /**
  44.   * Adding an Element before the specific Element
  45.   * this = the element of the button
  46.   * */
  47. function add_before($this){
  48. //converting JS element to jQuery DOM
  49. $this = $($this)
  50.  
  51. // Getting the Parent DOM
  52. var _parent = $this.closest('.list-group-item')
  53.  
  54. //Generate New DOM
  55. var new_el = new_dom();
  56.  
  57. new_el.hide()
  58.  
  59. // Adding new element before the parent DOM
  60. _parent.before(new_el)
  61.  
  62. //Animate element for showing
  63. new_el.show('slideDown')
  64.  
  65. }
  66.  
  67. /**
  68.   * Adding an Element after the specific Element
  69.   * this = the element of the button
  70.   * */
  71. function add_after($this){
  72. //converting JS element to jQuery DOM
  73. $this = $($this)
  74.  
  75. // Getting the Parent DOM
  76. var _parent = $this.closest('.list-group-item')
  77.  
  78. //Generate New DOM
  79. var new_el = new_dom();
  80. new_el.hide()
  81. // Adding new element after the parent DOM
  82. _parent.after(new_el)
  83. //Animate element for showing
  84. new_el.show('slideDown')
  85.  
  86. }
  87.  
  88. /**
  89.   * generating new Text of an Element
  90.   * this = the element of the button
  91.   * */
  92.  
  93. function regenerate_text($this){
  94. //converting JS element to jQuery DOM
  95. $this = $($this)
  96.  
  97. // Getting the Parent DOM
  98. var _parent = $this.closest('.list-group-item')
  99.  
  100. // getting the DOM of the element that holds the text
  101. var h3 = _parent.find('h3')
  102.  
  103. var new_key = random_key();
  104. h3.text(`Example New Generated Key #${new_key}`);
  105. }
  106.  
  107. /**
  108.   * Removing the Parent Element
  109.   * this = the element of the button
  110.   * */
  111.  
  112. function remove_item($this){
  113. //converting JS element to jQuery DOM
  114. $this = $($this)
  115.  
  116. // Getting the Parent DOM
  117. var _parent = $this.closest('.list-group-item')
  118.  
  119. // Removing the DOM
  120. _parent.remove()
  121. }

Snapshot

Here's the snapshot of the result of the given source code of the sample web application.

JS DOM Manipulation

DEMO VIDEO

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.

Happy Coding :)

Add new comment