Cover Image for jQuery append() method
159 views

jQuery append() method

The jQuery append() method is used to insert content at the end (the last child) of each selected element. It allows you to add new elements or text after the existing content of the selected elements.

The syntax for using the append() method is as follows:

To insert HTML content:

$(selector).append(content);

To insert DOM elements or jQuery objects:

$(selector).append(element1, element2, ...);
  • selector: It is a string that specifies the elements to be selected.
  • content: It can be an HTML string, a DOM element, a jQuery object, or text that you want to insert after the content of the selected elements.

Here’s an example of how you can use the append() method:

HTML:

<div id="myDiv">
  <p>This is some text inside the div.</p>
</div>

JavaScript:

// Append a new paragraph element to the div
$('#myDiv').append('<p>After the existing text.</p>');

After executing the above JavaScript code, a new p element will be inserted at the end of the div element with the ID “myDiv”:

Resulting HTML:

<div id="myDiv">
  <p>This is some text inside the div.</p>
  <p>After the existing text.</p>
</div>

You can also use append() to insert existing DOM elements or jQuery objects:

// Create a new paragraph element
var newParagraph = $('<p>After the existing text.</p>');

// Append the new paragraph element to the div
$('#myDiv').append(newParagraph);

In this example, we first create a new p element using jQuery and then use append() to insert it at the end of the div with the ID “myDiv.”

The append() method is useful when you want to dynamically add content to the end of elements, such as inserting new elements or text after existing content. It is commonly used in conjunction with other jQuery methods and event handlers to create interactive and dynamic web pages.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS