In this post, we will learn how to add new element to DOM in jQuery. So how we can do this, we will learn in this post.


How To Add New Element To DOM In jQuery ?


Add New Element To DOM

To add or insert new element to DOM, we use  append()  or  prepend()  jQuery methods. The append() method add element at the end of the content and the prepend() method add element at the beginning of the content. So how these methods work we will see in the given example.


<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>How To Add New Element To DOM In jQuery ?</title>
</head>
<body>

<ol>
<li>list item</li>
<li>list item</li>
<li>list item</li>
</ol>

<br/><br/>

<button type="button" id="appendItem">Append New Element</button>

<button type="button" id="prependItem">Prepend New Element</button>


<!-- jQuery CDN -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>


<script>

$(document).ready(function(){

//append list item
$("#appendItem").click(function(){
$("ol").append("<li>Append list item at the end</li>");
});

//prepend list item
$("#prependItem").click(function(){
$("ol").prepend("<li>Prepend list item at the beginning</li>");
});

});

</script>
</body>
</html> code-box



Summary

In this post we learned how to add new element to DOM in jQuery. You try to make it yourself. I hope you make. If you face any problem, then comment and tell us. Keep visiting the blog to read more similar posts.  

Post a Comment

Previous Post Next Post