.after()
In this chapter you will learn:
- Syntax and Description for .after() method
- How to insert text node after paragraph
- How to insert hard coded HTML element
- How to insert a selected node from the same HTML document
Syntax and Description
.after(content)
content: An element, HTML string, or jQuery object to insert after each matched element.after(function)
function: A function that returns an HTML string to insert after each matched element
.after()
method inserts content specified by
the parameter after each element in the set of matched elements.
Consider the following HTML code:
<div class="container">
<h2>Header</h2>
<div class="inner">Hello</div>
<div class="inner">InnerText</div>
</div>
The following code creates content and insert it after several elements at once.
$('.inner').after('<p>Test</p>');
The Results would be:
<div class="container">//from j a v a2 s . c om
<h2>Header</h2>
<div class="inner">Hello</div>
<p>Test</p>
<div class="inner">InnerText</div>
<p>Test</p>
</div>
The following code selects an element on the page and inserts it after another.
$('.container').after($('h2'));
The results would be:
<div class="container">
<div class="inner">Hello</div>
<div class="inner">InnerText</div>
</div>
<h2>Header</h2>
Its return value is the jQuery object, for chaining purposes.
Insert text node
The following code adds text node created from
document.createTextNode
after selected paragraph.
<html><!--from j ava 2s . c o m-->
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("p").after( document.createTextNode("Hello") );
});
</script>
</head>
<body>
<body>
<p> a</p><b>b</b>
</body>
</html>
Insert hard coded HTML element
The following code inserts hard coded HTML element after a paragraph..
<html><!-- j a v a 2 s .c om-->
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("p").after("<b>Hello</b>");
});
</script>
</head>
<body>
<body>
<p> a</p><b>b</b>
</body>
</html>
Insert a selected node
The following code switches the sequence of two tags.
<html><!--from j a v a 2s .com-->
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("p").after( $("b") );
});
</script>
</head>
<body>
<body>
<b>b</b>
<p>p</p>
</body>
</html>
Next chapter...
What you will learn in the next chapter:
- Syntax and Description for .andSelf() DOM method
- How to reference current and next element
- How to add tag back and move on