JQuery Create Element

With JQuery, We can easily create different HTML elements and also insert them into components.

<!DOCTYPE html>
<html>
<head>
    <title>Errorsea - jquery create element</title>
</head>
<body>

</body>
</html>

Above structure is the basic HTML structure that contains the head and body. To use jquery in HTML code, we require jquery google CDN in head or body section.

Step 1:

So, first, insert the following CDN into head tag.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

Note: We require above CDN in our code. JQuery CDN requires an active internet connection.

<!DOCTYPE html>
<html>
<head>
	<title>Errorsea - jquery create element</title>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>

</body>
</html>      

Step 2:

Suppose we want to insert a paragraph inside body tag using jquery.

Here, we create elements using jquery as follows:

<script>
	$(document).ready(function(){
		var p1 = $("<p>This is a paragraph</p>");
		$("body").append(p1);
	});
</script>

Explanation:

  • First-line shows that function will run during loading of the HTML page.
  • We create an element <p> and store it in a variable p1.
  • We append this new element inside the body tag.

Example 1

<!DOCTYPE html>
<html>
<head>
	<title>Errorsea - jquery create element</title>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> 
</head>
<body>
	<script>
		$(document).ready(function(){
			var p1 = $("<p>This is a paragraph</p>");
			$("body").append(p1);
		});
	</script>
</body>
</html> 

Example 2

We can also insert the second paragraph inside the newly created paragraph using jquery.

<script>
	$(document).ready(function(){
		var p1 = $("<p>This is a paragraph</p>");
		var p2 = $("<b>This is inside paragraph</b>");
		p1.append(p2);
 		$("body").append(p1);
	});
</script>

Explanation:

  • First-line shows that function will run during loading of the HTML page.
  • We create an element <p> and store it in a variable p1.
  • We create another element <b> and store it in a variable p2.
  • Then we append p2 variable inside p1 variable.
  • Finally, We append this new element inside the body tag.
<!DOCTYPE html>
<html>
<head>
    <title>Errorsea - jquery create element</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
	<script>
		$(document).ready(function(){
			var p1 = $("<p>This is a paragraph.</p>");
			var p2 = $("<b>This is inside paragraph</b>");
			p1.append(p2);
			$("body").append(p1);
		});
	</script>
</body>
</html>      

Read Also: JQuery Remove Element

Leave a Reply

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