jQuery

How to add DOM element in jQuery

In this tutorial, we are going to see how to add dom element in jQuery. You can add or insert elements into the DOM using two jQuery append() or prepend() methods. The append() method inserts content at the end of matching elements, while the prepend() method inserts content at the beginning of matching elements.

The following example will show you how to easily add new items to the end of a list using jQuery’s append() method.
 

How to add DOM element in jQuery
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>How to add DOM element in jQuery</title>
		<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
		<script type="text/javascript">
			$(document).ready(function(){
				$("button").click(function(){
					$("ul").append("<li>lorem ipsum</li>"); 
				});
			});
		</script>
	</head>
	<body>
		<button>Add item</button>
		<ul>
			<li>lorem ipsum</li>
			<li>lorem ipsum</li>
			<li>lorem ipsum</li>
		</ul>
	</body> 
</html>
Result
  • lorem ipsum
  • lorem ipsum
  • lorem ipsum
 
In the same way, you can add elements at the beginning of the corresponding elements.

The following example will show you how to add an HTML header at the start of a paragraph using jQuery’s prepend() method.

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>How to add DOM element in jQuery</title>
		<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
		<script type="text/javascript">
			$(document).ready(function(){
				$("button").click(function(){
					$("p").prepend("<h1>This is a title</h1>"); 
				});
			});
		</script>
	</head>
	<body>
		<p>This is a paragraph.</p>
		<button>Add a title</button>
	</body> 
</html>
Result

This is a paragraph.

mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *