Create Div Tag & Elements After Another Div Tag In jQuery
- In jQuery the after (content) method is used for inserting the content after each of the matched elements.
Syntax:
$(selector).after(content,function(index))
Parameter
|
Description
|
content
|
Required.
Specifies the content to insert (can contain HTML tags)
Possible
values:
ü
HTML
elements
ü
jQuery
objects
ü
DOM
elements
|
function(index,html)
|
Optional.
ü
index - Returns the index position of the
element in the set
|
Sample Code:
<!DOCTYPE html>
<html>
<head>
<title>
wikitechy-create controls dynamically in jquery
</title>
<script src="http://code.jquery.com/jquery.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").after("Text inserted after div Tag<br />");
});
});
</script>
</head>
<body>
<button>WikiTechy - Add new controls and div element dynamicaly</button>
<p>Click above button to dynamically add div element below</p>
<div id="SecondPara">Hi from Wikitechy</div>
</body>
</html>
Code Explanation:
Inside the <script src= ” http://code.jquery.com/jquery.js “> </script> the ajax library has been called using the (src)=source attribute.
Here we have created the element button,paragraph and div section.
The $(document).ready(function); - specifies that the document to be fully loaded and ready before working with it, in order to prevent any jQuery code from running before the document is finished loading.
$("button").click(function(){ - here is the button click event, which has been called here as element selector whose element “button” has been assigned for the click function.
Here we are use the element selector “div” and we assign the after function for the element “div”. So the text will be appended after the div element.
Sample Output:
Here in this output we have shown the button” WikiTechy - Add new controls and div element dynamically” initially there is no div element which will be added dynamically as shown here.
Here in this output we have shown the button” WikiTechy-Add new list item” clicked for 1st time where the new div element “Text inserted after div tag” has be added after the text “Hi from wikitechy” in the window as shown.
Similarly, here in this output we have shown the button” WikiTechy-Add new list item” clicked for 2nd time where the new div element “Text inserted after div tag” has be added after the text “Hi from wikitechy” in the window as shown.