Page Content

Tutorials

Understanding the DOM in jQuery With Code Example

DOM in jQuery

DOM in jQuery
DOM in jQuery

JavaScript needs the DOM to update web pages. Every HTML element, attribute, and text is a node in this tree. Program the page’s content, appearance, and structure with this object-based paradigm.

Understanding the DOM Structure

The relationships between the items in the DOM resemble a family tree. The example is

  • In the DOM, elements have relationships similar to a family tree. For instance:
  • The <html> element is the ancestor of all other elements in the document.
  • Elements like <head> and <body> are children (and descendants) of <html>.
  • A parent element is the direct container of an inner element, while a child element is directly nested inside a parent.

Elements at the same level, sharing a common parent, are considered siblings (e.g., multiple <p> elements within a <div>). This hierarchical structure allows for precise targeting and manipulation of specific parts of a web page. Certain sections of a web page can be precisely targeted and altered because to this hierarchical structure.

jQuery’s Role in DOM Interaction

Multiple lines of code and browser-specific problems are common when using simple JavaScript to interface directly with the DOM. For fast web development, jQuery, a “fast and concise JavaScript Library” speeds up Ajax interactions, event handling, HTML page traversal, and animation. It provides a consistent approach to access and alter things to compensate for browser quirks and conventional access techniques.

Here’s how jQuery enhances working with the DOM:

Simplified Selection

The $() function, which is a shorthand for the jQuery object, is the fundamental factory function of jQuery. Developers may swiftly find objects by tag name, ID, class, attributes, or location using a CSS selector expression. JQuery methods implicitly loop through a given collection of components, unlike vanilla JavaScript, which often requires explicit iteration (such as a for loop).

Tag Name Selector: Chooses all components that match a specified HTML tag (for example, $(‘p’) chooses all paragraphs).

ID Selector: ID selectors choose one unique element (e.g., $(‘#some-id’)). The jQuery selector uses #, although the HTML ID attribute does not.

Class Selector: The jQuery Class Selector selects HTML items by CSS class. Use this selector to target all document elements with a class property. If many div elements or even strong and p tags have the same class attribute, the Class Selector can select them all. The jQuery class selection is distinguished by a period (.) before the class name.

Universal Selector: The asterisk (*) symbol in jQuery stands for the Universal Selector. Selecting every HTML element that is present in a document is its main purpose. The , , and tags are among the basic structural components included in this extensive assortment.

Multiple Elements Selector: The jQuery Multiple Elements Selector selects the results of multiple selectors. It lets you aggregate any number of selectors into one result set. DOM elements in the jQuery object may not be in the same order as in the document.

DOM Traversal Methods

jQuery offers techniques for navigating the DOM tree from a chosen element to its relatives. A few examples are:

  • parent(): Retrieves an element’s direct parent.
  • children(): Returns each matched element’s immediate children.
  • find(): Looks for descendant elements that match a selector.
  • The next and previous sibling components are obtained using the next() and prior() functions.

DOM Manipulation Methods

There are many different ways to modify the structure, attributes, and content of elements with jQuery. Among the most important instances are

  • HTML(): Retrieves or modifies an element’s HTML content.
  • text(): Removes HTML tags from items to retrieve or set their plain text content.
  • val(): Returns or modifies the value of the form fields.
  • HTML attribute attr() returns or alters its value.
  • These functions add, remove, and toggle CSS classes on objects.
  • Content is inserted into elements using the append() and prepend() functions, respectively.
  • Deleting matched items and their offspring from DOM.

$(document).ready(): To limit jQuery code to when the HTML document loads and the DOM is established, use $(document).ready(). This blocks scripts from accessing pre-DOM components. $(document).ready() launches immediately after the DOM tree is formed, making it more reliable than window.onload, which waits for all relevant like photos to load. Also known as $(function() { // jQuery methods here…});.

Code Sample: Using jQuery to Show DOM Interaction

The example that follows illustrates how jQuery makes it easier to handle events, access elements, and edit content in the DOM:

Example:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>jQuery Button Click Example</title>
  <! jQuery from official CDN >
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script>
    // Wait until the page is fully loaded
    $(document).ready(function() {
      // Button A
      $("#a").click(function() {
        $("#output").html("Boring :-(");
      });
      // Button B
      $("#b").click(function() {
        $("#output").html("A nice game :-)");
      });
      // Button C
      $("#c").click(function() {
        $("#output").html("How about a nice game of chess?");
      });
    });
  </script>
</head>
<body>
  <h2>Click a Button:</h2>
  <button id="a">Option A</button><br><br>
  <button id="b">Option B</button><br><br>
  <button id="c">Option C</button><br><br>
  <hr>
  <!-- Output area -->
  <div id="output" style="font-size: 20px; color: green;"></div>
</body>
</html>

Output:

Click a Button:
Option A
Boring :-(
Option B
A nice game :-)
Option C
How about a nice game of chess?

This example, illustrates the core functionalities:

$(document).ready(): To ensure that the HTML document is completely parsed and prepared for modification prior to any script execution, all jQuery code is inside this function.

Selectors (ID-based): The ID-based selectors $(“#a”), $(“#b”), $(“#c”), and $(“#output”) are used to pick particular HTML components based on their distinct IDs. The jQuery function can be shortened with the $ symbol.

Event Handling (.click()): Each button’s selection has the.click() method attached, which contains the capability of a onclick event handler. This enables the website to respond to user input.

DOM Manipulation (.html()): Without any arguments,.html() functions as a getter, giving back a string representation of the first matching element’s HTML content (or innerHTML). This implies that it will incorporate any HTML tags that are contained in the content of the element.

By eliminating the complexity and inconsistencies of native JavaScript and various browsers, jQuery essentially makes the process of choosing, navigating, and modifying the DOM much more effective and accessible.

Kowsalya
Kowsalya
Hi, I'm Kowsalya a B.Com graduate and currently working as an Author at Govindhtech Solutions. I'm deeply passionate about publishing the latest tech news and tutorials that bringing insightful updates to readers. I enjoy creating step-by-step guides and making complex topics easier to understand for everyone.
Index