How to create new element by JQuery and JavaScript in DOM
Create new element
using JavaScript and JQuery in DOM
We know HTML is used to represent data to user interface in
web application. In old days the web pages were very static in nature. There
was not much scope to create web page dynamically by taking data from various
data sources.
But time has changed and in modern days it’s tough to get
static web application. Means almost all modern web applications are dynamic in
nature. Now question is “How to generate HTML element dynamically?”
Think about one application where people can see
number of comments in particular article given by reader. Now during
development, developer will not know how many comments are going to be for a post. So, the
developer has to create something which would change in dynamically. This is
one general scenario of dynamic web application.
By client side technology we can create dynamic element and can
attach in DOM by both JavaScript and JQuery. In this article we will see sample
example to do same.
Create element by
JavaScript
<html>
<head>
</head>
<body>
<div id="div1">
<p id="p1">This is a Static element</p>
</div>
<script>
var para=document.createElement("p");
var node=document.createTextNode("This is Dynamic element");
para.appendChild(node);
var element=document.getElementById("div1");
element.appendChild(para);
</script>
</body>
</html>
In this example, we have seen how to create simple <p>
element using JavaScript. Below code will create HTML element.
var para=document.createElement("p");
Now, after creating element we have to attach it to existing
DOM element. Here, we are attaching this element to existing <DIV> element.
Create Dynamic
element by JQuery
In previous example we have seen how to create dynamic
element in JavaScript and now we will see how to create element by JQuery
dynamically.
As we know JQuery is nothing but JavaScript’s library and
very power to manipulate DOM (Document Object Model).
At first you have to give link of JQuery API in your
application to work with JQuery . I have used google’s JQuery SDN for me. If
you want, you can download JQuery file (basically JavaScript file) in your
computer and host locally.
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</head>
<body>
<div id="div1">
<p id="p1">This is a Static element</p>
</div>
<script>
$("#div1").append("<p>This is dynamic element by JQuery</p>")
</script>
</body>
</html>
This example is pretty simple to understand. Below code will
create and append element into existing DOM element.
$("#div1").append("<p>This is dynamic
element by JQuery</p>")
Here div1 is already present and in run time one <p>
tag will get create within it.
Conclusion:
This is simple example to create dynamic element by
JavaScript and JQuery . In real world, you might encounter more tough
situation and might need to create complex dynamic set of elements.