Hello Readers,
We can use .after() and .before() methods for different tasks.
If we want to add any other HTML tag or content after or before define HTML tag, then we can use these jquery methods for the same tasks.
Example: method after()
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").after("<span class='addSpan'>Hello World!</span>");
});
});
</script>
</head>
<body>
<button>Insert content after each p element</button>
<p class="first">This is a paragraph.</p>
<p class="second">This is another paragraph.</p>
</body>
</html>
Example: method before()
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").before("<span class='addSpan'>Hello World!</span>");
});
});
</script>
</head>
<body>
<button>Insert content after each p element</button>
<p class="first">This is a paragraph.</p>
<p class="second">This is another paragraph.</p>
</body>
</html>
We can see in above both examples, we have used after() and before() methods for adding HTML tag and content after and before existing HTML tags.
If we want to move HTML tags up and down, then after() and before() also useful for this type of task.
Here you can check following example for the same task.
Example 1: before() method for moving up HTML tag
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p.first").before($(".second"));
});
});
</script>
</head>
<body>
<button>Insert content after each p element</button>
<p class="first">This is a paragraph.</p>
<p class="second">This is another paragraph.</p>
</body>
</html>
Example 2: after() method for moving down HTML tag
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p.second").after($(".first"));
});
});
</script>
</head>
<body>
<button>Insert content after each p element</button>
<p class="first">This is a paragraph.</p>
<p class="second">This is another paragraph.</p>
</body>
</html>
Thanks
0 Comment(s)