Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is the difference between jQuery add() & jQuery append() methods in jQuery?
The jQuery add() and jQuery append() methods serve different purposes in jQuery. The add() method is used to combine elements into a single jQuery selection, while the append() method is used to insert content inside existing elements.
jQuery add() Method
The add() method adds elements to an existing group of elements, creating a combined selection. This allows you to apply the same operation to multiple different elements at once.
Example
You can try to run the following code to learn how to work with the jQuery add() method ?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("h1").add("span").css("background-color", "yellow");
});
</script>
</head>
<body>
<h1>Tutorialspoint</h1>
<p>Text Tutorials for free.</p>
<span>Video Tutorials for free.</span>
</body>
</html>
In this example, the add() method combines the h1 element with the span element, and both receive a yellow background color.
jQuery append() Method
The append() method inserts content at the end of the inside of every matched element. It adds new content as the last child of the selected elements.
Example
You can try to run the following code to learn how to work with the jQuery append() method ?
<!DOCTYPE html>
<html>
<head>
<title>jQuery append() method</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("div").click(function () {
$(this).append('<div class="div"></div>');
});
});
</script>
<style>
.div {
margin: 10px;
padding: 12px;
border: 2px solid #666;
width: 60px;
}
</style>
</head>
<body>
<p>Click on any square below to see the result:</p>
<div class="div" style="background-color: blue;"></div>
<div class="div" style="background-color: green;"></div>
<div class="div" style="background-color: red;"></div>
</body>
</html>
In this example, clicking on any colored square will append a new div element inside the clicked element.
Key Differences
The main difference is that add() combines elements into a single selection for applying operations, while append() inserts new content inside existing elements. Use add() when you want to select multiple elements, and append() when you want to insert content.
Conclusion
Understanding the difference between add() and append() is essential for effective jQuery manipulation. The add() method combines selections, while append() inserts content into elements.
