.replaceAll()
In this chapter you will learn:
Syntax and Description
.replaceAll(target)
replaces each target element with the set of matched elements.
target
is a selector expression indicating which element(s) to replace
Its return value is the jQuery object, for chaining purposes.
For the following HTML elements
<div class="container">
<div class="first">Hello</div>
<div class="second">And</div>
<div class="third">InnerText</div>
</div>
The following code selects an element to use as the replacement:
$('.first').replaceAll('.third');
This results:
<div class="container">
<div class="second">And</div>
<div class="first">Hello</div>
</div>
Replace all paragraphs
The following code replaces all paragraph with hard coded element.
<html><!-- j av a 2 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(){
$("<b>Paragraph. </b>").replaceAll("p");
});
</script>
<style>
div { border:2px green solid;}
</style>
</head>
<body>
<body>
<p>Hello java2s.com</p>
</body>
</html>
Replace all in click event
<html><!--from j a v a 2 s. com-->
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type='text/javascript'>
$(document).ready(
function() {
$('input#tmpQuote1').click(
function($e) {
$e.preventDefault();
$('p#id1').replaceAll(this);
}
);
$('input#tmpQuote2').click(
function($e) {
$e.preventDefault();
$('p#id2').replaceAll(this);
}
);
}
);
</script>
<style type='text/css'>
div {
background: #acf7d0;
border: 3px solid #96dab6;
margin: 3px;
}
div#tmp {
display: none;
}
</style>
</head>
<body>
<div id='tmp'>
<p id='id1'>
java2s.com
</p>
<p id='id2'>
java2s.com
</p>
</div>
<div>
<input type='submit' id='tmpQuote1' value='View Quote' />
</div>
<div>
<input type='submit' id='tmpQuote2' value='View Quote' />
</div>
</body>
</html>
Next chapter...
What you will learn in the next chapter:
- Syntax and Description for .replaceWith()
- Change the tag with replaceWith
- Replace with hard coded tag
- Replace in click event
- Change button text