jQuery DOM Insertion Tutorial šŸŽÆ

beginner
9 min

jQuery DOM Insertion Tutorial šŸŽÆ

Welcome to our comprehensive guide on jQuery DOM Insertion! This tutorial is designed for beginners and intermediates, so let's dive right in!

Understanding the Document Object Model (DOM) šŸ“

The DOM represents the structure of a web page, allowing developers to manipulate the content, HTML, and CSS dynamically. jQuery simplifies this process by providing a concise, cross-browser compatible way to work with the DOM.

Basic DOM Manipulation with jQuery šŸ’”

Selecting Elements

To manipulate elements, we first need to select them. Here's how to select an element by its ID using jQuery:

javascript
// Select an element with ID "example" var element = $("#example");

šŸ“ Note: $ is the shorthand for jQuery.

Inserting Elements

Now that we've selected an element, let's learn how to insert new content into the DOM.

Inserting HTML

To insert HTML into the DOM, we can use the .html() function:

javascript
// Insert new HTML into the selected element element.html("<p>Hello, World!</p>");

Inserting Text

For simple text insertion, use the .text() function:

javascript
// Insert new text into the selected element element.text("Hello, World!");

Practical Example šŸ“

Let's create a simple page with a button and a div. When the button is clicked, we'll insert a new paragraph into the div:

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>DOM Insertion</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <button id="insertButton">Insert Paragraph</button> <div id="content"></div> <script> $(document).ready(function() { // Select the button and div var button = $("#insertButton"); var content = $("#content"); // Attach a click event to the button button.click(function() { // Insert a new paragraph into the div content.html("<p>Hello, World!</p>"); }); }); </script> </body> </html>

Quiz Time šŸŽÆ

Quick Quiz
Question 1 of 1

What does the `$` symbol represent in jQuery?

Quick Quiz
Question 1 of 1

Which jQuery function is used to insert HTML into an element?