Introduction to JQUERY - Changing Content with the replaceAll() and replaceWith() methods

Guest Posts Paolo Nikko Nuñal

Sometimes during programming, changing elements are sometimes used to manipulate HTML data. This is practice by many in handling error messages or changing any elements to processed data. JQUERY has two built in functions that can help you out in replacing elements thanks to the replaceWith() and replaceAll() methods. In this tutorial we are going to look how these methods work and how it is easy for you to replace HTML elements with specific data.

Syntax:

$(selector).replaceWith([CONTENT])

$(selector).replaceWith([CONTENT],FUNCTION]

CONTENT - (REQUIRED) Specifies the content to be inserted. This can also be in the form of HTML tags. Possible values include HTML Elements, JQUERY Objects, DOM elements.

FUNCTION(INDEX) - (OPTIONAL) Specifies a function that returns the content to be replaced. INDEX, returns the index position of the element found on the set.

Code


<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
      $(document).ready(function(){
          $("#btn-replace").click(function(){
                $("h4:first").replaceWith("Lone Ranger");
          });
});
</script>
</head>
<body>
<h4>first header</h4>
<h4>middle header</h4>
<h4>last header</h4>


<button type="button" id="btn-replace">Replace</button> </body> </html>


In the example above, we have three <h4> headers. When you click on the "
Replace button, the have the selector to change only the first header with the text "first header" with the new text "Lone Ranger".  The replacewith() method is good for selecting specific elements. However, if you want to replace many elements you can use the replaceAll() method.

Syntax:

$([CONTENT]).replaceAll(selector)

CONTENT - (REQUIRED) Specifies the content to be inserted. Must contain HTML tag.

SELECTOR - (REQUIRED) Specifies the elements that needs to be changed.

Code


<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
      $(document).ready(function(){
          $("#btn-replace").click(function(){
               $("<h1>CHANGED to H1</h1>").replaceAll("h5");
           });
       });
</script>
</head>
<body>
<button type="button" id="btn-replace">Replace</button>
<h5>First header.</h5>
<h5>Middle header</h5>
<h5>Last header</h5>
</body>
</html>


In this example, we changed all <h5> headers to an <h1> header as well as the text to "CHANGED to H1". The replaceAll() method is useful if you are planning on manipulating bulk HTML elements.