jQuery .insertBefore() method inserts element before selected elements
Syntax and Description
.insertBefore(target)
inserts every element in the set of matched elements
before the target.
target
is a selector, element, HTML string,
or jQuery object; the matched set of elements will be
inserted before the element(s).
Return value is the jQuery object, for chaining purposes.
Consider the following HTML code:
<div class="container">
<h2>Header</h2>//from w ww . j a va 2s .c o m
<div class="inner">Hello</div>
<div class="inner">InnerText</div>
</div>
When we apply the following code
$('<p>Test</p>').insertBefore('.inner');
The results would be:
<div class="container">
<h2>Header</h2>//ww w. j av a2 s .c o m
<p>Test</p>
<div class="inner">Hello</div>
<p>Test</p>
<div class="inner">InnerText</div>
</div>
To select an element on the page and insert it before another we can use the following code.
$('h2').insertBefore($('.container'));
The results would be:
<h2>Header</h2>//from w ww . j av a 2 s.co m
<div class="container">
<div class="inner">Hello</div>
<div class="inner">InnerText</div>
</div>
Switch the node sequence
The following code inserts selected element before.
<html>
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){<!--from ww w . java 2 s . c o m-->
$("p").insertBefore("#foo");
});
</script>
</head>
<body>
<body>
<p>a</p><div id="foo">java2s.com</div>
</body>
</html>
.insertBefore is the reverse of .before
The reverse of $(A).before(B)
<html>
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){<!-- ww w .j a v a 2 s . co m-->
$("p").insertBefore( $("b") );
});
</script>
</head>
<body>
<body>
<b>java2s.com</b>
<p>java2s.com:</p>
</body>
</html>