In jQuery, you can create new elements dynamically using the $()
function or the jQuery()
function. When you pass a string containing HTML as the first parameter, this function will create a new element:
$("<a>")
The syntax for creating a new element using jQuery is as follows:
$("<element>")
: The dollar sign ($
) followed by parentheses is the jQuery function that creates a new element. Inside the parentheses, you specify the name of the element you want to create, wrapped in quotes (e.g.,"<div>"
,"<a>"
,"<img>"
).{ attributes }
: Optionally, you can provide a JavaScript object within the curly braces to specify attributes and content for the new element. Each attribute is defined as a key-value pair, where the key represents the attribute name, and the value represents the attribute value.
jQuery creates element example
Simple example code that demonstrates creating elements using jQuery and appending them to the body:
<!DOCTYPE html>
<html>
<head>
<title>jQuery Create Element Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
// Create a new <div> element
var newDiv = $("<div>");
// You can also specify attributes and content for the new element
var newLink = $("<a>", {
href: "https://example.com",
text: "Click me"
});
// Append the new elements to the body element
$("body").append(newDiv);
$("body").append(newLink);
});
</script>
</head>
<body>
<h1>jQuery Create Element Example</h1>
<!-- Elements will be appended here -->
</body>
</html>
Output:
You can then manipulate the elements further, add more attributes, or append them to the document as needed.
Do comment if you have any doubts or suggestions on this jQuery code.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version