In this article, I will show how to add a new element to an existing array using jQuery, To add the new elements we need the Javascript array function.
First Method
If you want to add the new elements at the last position of the array you can use the "PUSH" function. With the help of this function, you can add one or one more element at the last position of the array.
First, we add one element to the array
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery | array</title>
<style>
*
{
background: #212529;
font-family: sans-serif;
font-weight: bold;
color: #fff;
}
</style>
</head>
<body>
<script src="asset/jquery.min.js"></script>
<script>
$(document).ready(function() {
var arr = [1, 34, 56, 767, 88];
console.table(arr);
// add only one element
arr.push(23);
console.table(arr);
});
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery | array</title>
<style>
*
{
background: #212529;
font-family: sans-serif;
font-weight: bold;
color: #fff;
}
</style>
</head>
<body>
<script src="asset/jquery.min.js"></script>
<script>
$(document).ready(function() {
var arr = [1, 34, 56, 767, 88];
console.table(arr);
// add only one or one more element
arr.push(23, 'HTML');
console.table(arr);
});
</script>
</body>
</html>
Second Method
If you want to add the new elements at the beginning position of the array you can use the "UNSHIFT" function. With the help of this function, you can add one or one more elements at the beginning position of the array.
Code for adding one element
Code for add one or one more elements
Third Method
- 3 is the index at which the splicing operation will begin.
- 0 indicates that no elements will be removed.
- 7.8 and 'Python' are the elements to be added at the specified index.
If you want to also remove the array elements you need the change the second parameter value, suppose you want to remove one element from the array so change the value 0 to 1, but it depends on your project requirement.