Jquery create new element
In jQuery, you can create a new element using the $()
function, which is used to create a new jQuery object. Here are a few ways to create a new element:
-
Using the
$()
function with a tag name:var newElement = $("<div>");
This will create a new
<div>
element. -
Using the
$()
function with a tag name and attributes:var newElement = $("<div id='myDiv' class='myClass'>");
This will create a new
<div>
element with anid
attribute set to "myDiv" and aclass
attribute set to "myClass". -
Using the
$()
function with a tag name and content:var newElement = $("<div>Hello World!</div>");
This will create a new
<div>
element with the content "Hello World!". -
Using the
jQuery
function (which is equivalent to$()
):var newElement = jQuery("<div>");
-
Using the
document.createElement()
method:var newElement = document.createElement("div");
This will create a new
<div>
element, but it will not be a jQuery object. You can wrap it in a jQuery object using the$()
function:var newElement = $(document.createElement("div"));
Note that when you create a new element using the
$()
function, it will be a jQuery object, which means you can use jQuery methods on it, such as.append()
,.appendTo()
,.html()
, etc.
Here is an example of creating a new element and appending it to the page:
var newElement = $("<div id='myDiv' class='myClass'>Hello World!</div>");
$("body").append(newElement);
This will create a new <div>
element with the content "Hello World!" and append it to the <body>
element of the page.