DOM Manipulation

JavaScript and a web page are interfaced by the Document Object Model(DOM), which represents HTML content as a tree. JavaScript is used to dynamically check, edit, add, or remove nodes and their contents in DOM manipulation. Basic JavaScript allows DOM access, but it often requires multiple characters to reach a single element or group, which is time-consuming and error-prone.
jQuery’s succinct and cohesive solution accounts for browser-dependent idiosyncrasies and adds capabilities that the pure DOM manipulation paradigm lacks, simplifying DOM handling. It offers a strong general-purpose abstraction layer for typical web scripting applications.
The primary DOM manipulation categories made possible by jQuery are as follows:
Accessing and Selecting Elements: $(), also known as the jQuery factory function, is used to access and select elements. This technique takes any CSS selector expression, making page parts and groups easy to find. $’p’ chooses all paragraph elements, $’#some-id’ selects things by ID, and $’.some-class’ selects items by class. With implicit iteration, jQuery functions on a selected collection automatically iterate through all matched elements without for loops.
Modifying Content: Content Modification jQuery provides ways to examine and modify node content:
- The html() method returns or sets the HTML content (including tags) of the first or all matched items.
- Remove HTML tags and get or modify elements’ raw text with text().
- Use val() to access or alter form field contents, including input values.
Modifying Attributes and Properties:
- This function retrieves or updates non-class attributes like id, rel, href.
- JavaScript uses prop() to get or set DOM manipulation properties, which differ from HTML attributes (className vs. class).
- addClass/removeClass adds or removes CSS classes from matched objects.
- ToggleClass() changes item classes.
- Checks if matched components are class-specific using hasClass().
Inserting Elements:There are several ways to add new elements in relation to preexisting ones using jQuery.
- add() and prepend(): Add material to elements’ ends or beginnings.
- Use after() or before() to insert information outside the matched components.
- prependTo(), insert, and appendTo()Insert (after())Prior to: Reversing the subject and target of the operation, these are “inverted” copies of the previous ones.
Removing Elements:
- Remove() removes matching elements and their descendants from the DOM.
- empty(): This function removes child nodes but leaves the matching elements’ parents.
- Like remove(), detach() allows you to keep the jQuery information related to the items that were removed so that they can be added back later .
Wrapping Elements:
- In an HTML structure, wrap() wraps each matched element separately.
- Wraps all matched HTML elements in a single unit.
- WrapInner() wraps each matched element’s children (including text nodes).
- Each matching element’s immediate parent is deleted via unwrap().
Cloning Elements: In jQuery, cloning components entails creating duplicates of pre-existing HTML elements on a webpage. The.clone() technique is the main tool for this. The matched components are duplicated when you use.clone(). You must then use one of jQuery’s insertion methods (such as insertAfter() or insertBefore()) to put these copied components onto the page; they won’t show up in the document by default.
Code Example:
This jQuery example dynamically changes and removes a webpage element’s CSS class and text.
<!DOCTYPE html>
<html>
<head>
<title>jQuery DOM Example</title>
<style>
.highlight {
background: yellow;
font-weight: bold;
padding: 10px;
}
</style>
<script src="https://code.jquery.com/jquery-1.8.2.min.js"></script>
<script>
$(function() {
$("#myElement").addClass("highlight").text("Modified and highlighted!");
$(".content p").append(" (Updated!)");
$("#myElement").after("<button id='removeBtn'>Remove</button>");
$("#removeBtn").click(function() {
$("#myElement, #removeBtn").remove();
alert("Content removed!");
});
});
</script>
</head>
<body>
<h2>jQuery DOM Example</h2>
<div id="myElement">Original content</div>
<div class="content">
<p>Paragraph 1</p>
<p>Paragraph 2</p>
</div>
</body>
</html>
Output:
jQuery DOM Example
Modified and highlighted!
Remove
Paragraph 1 (Updated!)
Paragraph 2 (Updated!)
Explanation of the Code
$(document).ready(function() { … });: This vital jQuery function ensures that its JavaScript code only runs once the page loads and the DOM manipulation is set up. Scripts trying to access non-DOM elements may cause problems.
$(“#myElement”).addClass(“highlight”).text;:
- With the id of myElement, $(“#myElement”): This selects the single div element using the ID selector.
- The CSS class highlight is added to the specified div using the.addClass(“highlight”) method. To give the element a dashing red border, bold text, and a yellow backdrop, the highlight class is defined in the <style> block.
- .text(“…”): The textual content of the same chosen div is then altered by this technique.
- This code is more efficient and concise because it demonstrates chaining, which calls several jQuery methods on the same selection in a single statement.
$(“.contentSection p”).append(” (Dynamically added!)”);:
- Using a descendent selector, $(“.contentSection p”) finds all p (paragraph) components that are inside any element of the class contentSection.
- The method.append(” (Dynamically added!)”) adds new material to each matching p element at the conclusion of the existing content.
$(“#myElement”).after(“<button id=’removeBtn’></button>”);: After the selected div element, fresh HTML content is inserted using the.after(“…”) technique. On the page, a new button is made with the ID removeBtn.
$(“#removeBtn”).click(function() { … });: The function “.click()” adds an event handler with the id=”removeBtn” to the button. When the button is pressed, the function within will run.
$(“#myElement, #removeBtn”).remove();:
- $(“#myElement, #removeBtn”): Selects “myElement” and “removeBtn” divs and buttons.
- Removes specified items and their contents with.remove(). the DOM.
- alert(“Content removed!”);: By confirming the action, a typical JavaScript alert box appears.
Why jQuery Works Well for DOM Manipulation
Using jQuery for DOM manipulation instead of JavaScript has many advantages:
Conciseness and Readability: Because jQuery can perform complex actions with fewer lines of code, scripts are easier to develop and comprehend.
Cross-Browser Compatibility: JQuery handles browser inconsistencies so your code runs across browsers without manual modifications.
Performance Optimization: Despite being slower than properly optimised vanilla JavaScript, jQuery speeds up element retrieval and other operations.
Feature-Rich API: Its feature-rich API unites event management, DOM manipulation, and animations.
Plugin Ecosystem:Developers can add hundreds of pre-existing plugins to the plugin ecosystem to make advanced interactive web production easier.
Conclusion
To sum up, jQuery simplifies activities that would otherwise be difficult and verbose in plain JavaScript by providing a succinct, effective, and strong foundation for DOM manipulation. jQuery improves code readability and development speed by streamlining dynamic element insertion or removal, attribute handling, content update, and element selection. It is a vital tool for developing dynamic, interactive, and responsive online applications because of its capacity to manage cross-browser inconsistencies as well as capabilities like chaining, event management, and a robust plugin ecosystem. All things considered, jQuery acts as a strong abstraction layer over the DOM, increasing the productivity and accessibility of front-end programming.