.prepend()
In this chapter you will learn:
- Syntax and Description for .prepend()
- How to add text node with prepend
- Insert to a span element
- Insert a selected element
Syntax and Description
.prepend
method inserts content at
the beginning of each element in the matched elements.
.prepend(content)
content: An element, an HTML string, or a jQuery object to insert at the beginning of each element in the set of matched elements.prepend(function)
function: A function that returns an HTML string to insert at the beginning of each element in the set of matched elements
Its return value is the jQuery object, for chaining purposes.
Add text node
The following code adds data to each tag with prepend.
<html><!-- j a v a 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(){
$("*", document.body).each(function () {
$(this).prepend(document.createTextNode("data"));
});
});
</script>
<style>
.y { background:yellow; }
</style>
</head>
<body>
<body>
<div><button disabled="disabled">First</button>
<span class="selected">java2s.com</span>
<span></span>
</div>
</body>
</html>
Insert to a span element
The following code inserts content to the inside of every matched element.
<html><!--from java2 s .c o m-->
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("span").prepend("<b>Hello </b>");
});
</script>
</head>
<body>
<body>
<span>span</span>
<div id="foo">FOO! java2s.com</div>
</body>
</html>
Insert a selected element
The following code inserts a selected element b
.
<html><!-- j a va 2 s. co m-->
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("p").prepend( $("b") );
});
</script>
</head>
<body>
<body>
<p> a</p><b>java2s.com</b>
</body>
</html>
Next chapter...
What you will learn in the next chapter: