This blog will see how we can add (appending) span tag/element inside div tag/element and add (wrapping) div tag/element outside the span tag/element dynamically using JQuery.
Let see in detail-
1. Add (appending) span tag/element inside div tag/element. Using .append() function we can add something in any element/tag inside.
<div id="div" class="div" style="height:150px; width:150px; background-color:red;"></div></br>
<button id='action'>Add span inside div</button></br>
JQuery code will be -
$('#action').click(function() {
$('.div').append("<span style='border-color: coral;background-color:green;'>Span Added</span>");//insert inside
});
2. Add (wrapping) div tag/element outside the span tag/element. Adding something outside of any element is called wrapping. For that we use .wrap() function.
<span class="span" style="background-color:green;">Span text</span></br>
<button id='action1'>Add div outside the span</button>
JQuery code will be -
$('#action1').click(function() {
$( ".span" ).wrap( "<div id='new' style='border: thick solid blue;' class='new'>Div Added..</div>" );//inser outside
});
Note: JQuery script will be writen before body close(</body>) tag.
Now complete example -
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
h3 {font-size: 30px;}
</style>
</head>
<body>
<center>
<h3>
Click to change
</h3>
<div id="div" class="div" style="height:150px; width:150px; background-color:red;"></div></br>
<button id='action'>Add span inside div</button></br>
<span class="span" style="background-color:green;">Span text</span></br>
<button id='action1'>Add div outside the span</button>
<script>
$('#action').click(function() {
$('.div').append("<span style='border-color: coral;background-color:green;'>Span Added</span>");//insert inside
});
$('#action1').click(function() {
$( ".span" ).wrap( "<div id='new' style='border: thick solid blue;' class='new'>Div Added..</div>" );//inser outside
});
</script>
</center>
</body>
</html>
No comments:
Post a Comment