How do I add a DOM element with jQuery?

javascript

You can use the jQuery append() method to add a new DOM element to an existing element. Here’s an example:

<!DOCTYPE html>
<html>
<head>
	<title>Example</title>
	<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
	<div id="myDiv">
		<p>This is some existing content.</p>
	</div>
	<script>
		$(document).ready(function(){
			var newElement = $("<p>This is the new element.</p>");
			$("#myDiv").append(newElement);
		});
	</script>
</body>
</html>

In this example, we have an existing div element with an id of myDiv that contains a p element with some text. We use the jQuery append() method to add a new p element with the text “This is the new element.” to the div element.

To create a new element with jQuery, we can use the $() function and pass in a string representing the HTML code for the new element, or pass in a reference to an existing element. In this example, we create a new p element using $(”

This is the new element.

”). We then pass this element to the append() method, along with a reference to the existing div element using the $(“#myDiv”) selector. This appends the new element as a child of the div element.

Note that you can also use other jQuery methods such as prepend(), after(), and before() to add elements in different positions relative to existing elements.