- Replace Text and DOM Elements in jQuery
- Replace Text and DOM Elements in jQuery
- Use the replace() Method to Replace Text in jQuery
- Use the replaceAll() Method to Replace DOM Elements in jQuery
- Use the replaceWith() Method to Replace DOM Elements in jQuery
- Related Article — jQuery Text
- .replaceAll()
- version added: 1.2 .replaceAll( target )
- Additional Notes:
- Example:
- Demo:
- Books
- Replace text with jQuery [with examples]
- Examples replacing strings in jQuery:
- Replace the text of an element on click:
- Replace multiple appearances of the same string
- Replace multiple words at the same time
- Replace case-insensitive text
- Replace a word in multiple texts
- Remove text using replace
- Replace a whole text, word, or sentence
- Replace HTML string with jQuery
- Conlusion
- Related articles
Replace Text and DOM Elements in jQuery
- Replace Text and DOM Elements in jQuery
- Use the replace() Method to Replace Text in jQuery
- Use the replaceAll() Method to Replace DOM Elements in jQuery
- Use the replaceWith() Method to Replace DOM Elements in jQuery
jQuery has different methods to perform the replace functionality. This tutorial demonstrates how to replace text or DOM elements in jQuery.
Replace Text and DOM Elements in jQuery
jQuery has functionalities to replace a string with another or a DOM element with another. The replace() method can replace a string in a sentence or group of strings.
The replace() method can only replace the first instance. If we want to replace all the string occurrences, a global modifier is used.
Similarly, jQuery offers a method to replace the DOM element with another. The methods replaceAll() , and replaceWith() can be used to replace DOM elements.
The replaceAll() method can replace each target element with a set of elements. The replaceWith() method can replace each element with the new content; it will return the set of removed elements.
The syntaxes for these methods are:
To replace a text using the replace() method:
string.replace (/[old string]/+/g, 'new string')
To replace a target element using the replaceAll() method:
$(content).replaceAll(selector)
To replace the selected content using the replaceWith() method:
$(selector).replaceWith(content, function(index))
Where g in the replace() method represents the global modifier. The content is mandatory in each method, which will specify if the input is a string, HTML elements, or jQuery objects.
Use the replace() Method to Replace Text in jQuery
As mentioned above, the replace() method can be used to replace a string or substring. Let’s try an example:
html lang="en"> head> meta charset="utf-8" /> title>jQuery Replace() Methodtitle> head> script src="https://code.jquery.com/jquery-1.12.4.js">script> script type="text/javascript"> $(document).ready(function () $(".SubElement span").text(function (index, text) return text.replace("delftstack", "www.delftstack.com"); >); >); script> style> #MainDiv width: 800px; height: 400px; background-color: lightblue; padding-top: 30px; padding-left: 10px; font-size: 40px; text-align: center; color: black; > style> head> body> div id="MainDiv"> div class="SubElement"> h2 style="color: green;"> jQuery Replace() Method Example h2> hr /> br /> span>Hello, This is delftstackspan> div> div> body> html>
The code above will replace the delftstack from the span to the www.delftstack.com . See output:
Use the replaceAll() Method to Replace DOM Elements in jQuery
The replaceAll() method will replace each element with the set of matched elements. Let’s try an example:
html> head> title>jQuery ReplaceAll Methodtitle> script src="https://code.jquery.com/jquery-1.12.4.js">script> script> $(document).ready(function () $("button").click(function () $("The Paragraph is replaced
").replaceAll("p"); >); >); script> style> #MainDiv width: 800px; height: 400px; background-color: lightblue; padding-top: 30px; padding-left: 10px; font-size: 30px; text-align: center; color: black; > style> head> body> div id="MainDiv"> h2>jQuery ReplaceAll Methodh2> p>This is paragraph Onep> p>This is paragraph Twop> p>This is paragraph Threep> button>Click to see changebutton>br /> div> body> html>
The code above will replace all the paragraphs in the given div with the given paragraph. See output:
Use the replaceWith() Method to Replace DOM Elements in jQuery
The replaceWith() method is used to replace each element in the set of matched elements with the given new content. See example:
html> head> title>jQuery ReplaceWith() Methodtitle> script src="https://code.jquery.com/jquery-1.12.4.js">script> script> $(document).ready(function () $("button").click(function () $("#DemoPara").replaceWith("www.delftstack.com"); >); >); script> style> #MainDiv width: 800px; height: 400px; background-color: lightblue; padding-top: 30px; padding-left: 10px; font-size: 30px; text-align: center; color: black; > style> head> body> div id="MainDiv"> h2>jQuery ReplaceWith Method Exampleh2> hr /> br /> p id="DemoPara">delftstackp> button id="button">Click here to replace the selected elementbutton> div> body> html>
The code above will replace the content from the selected element. This example replaces the content from the paragraph to www.delftstack.com .
Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.
Related Article — jQuery Text
.replaceAll()
Description: Replace each target element with the set of matched elements.
version added: 1.2 .replaceAll( target )
A selector string, jQuery object, DOM element, or array of elements indicating which element(s) to replace.
The .replaceAll() method is similar to .replaceWith() , but with the source and target reversed. Consider this DOM structure:
div class="container">
div class="inner first">Hello div>
div class="inner second">And div>
div class="inner third">Goodbye div>
div>
We can create an element, then replace other elements with it:
$( "
New heading
" ).replaceAll( ".inner" );
This causes all of them to be replaced:
div class="container">
h2>New heading h2>
h2>New heading h2>
h2>New heading h2>
div>
Or, we could select an element to use as the replacement:
This results in the DOM structure:
div class="container">
div class="inner second">And div>
div class="inner first">Hello div>
div>
From this example, we can see that the selected element replaces the target by being moved from its old location, not by being cloned.
Additional Notes:
Example:
Replace all the paragraphs with bold words.
html>
html lang="en">
head>
meta charset="utf-8">
title>replaceAll demo title>
script src="https://code.jquery.com/jquery-3.7.0.js"> script>
head>
body>
p>Hello p>
p>cruel p>
p>World p>
script>
$( "Paragraph. " ).replaceAll( "p" );
script>
body>
html>
Demo:
- Ajax
- Global Ajax Event Handlers
- Helper Functions
- Low-Level Interface
- Shorthand Methods
- Deprecated 1.3
- Deprecated 1.7
- Deprecated 1.8
- Deprecated 1.9
- Deprecated 1.10
- Deprecated 3.0
- Deprecated 3.2
- Deprecated 3.3
- Deprecated 3.4
- Deprecated 3.5
- Basics
- Custom
- Fading
- Sliding
- Browser Events
- Document Loading
- Event Handler Attachment
- Event Object
- Form Events
- Keyboard Events
- Mouse Events
- Class Attribute
- Copying
- DOM Insertion, Around
- DOM Insertion, Inside
- DOM Insertion, Outside
- DOM Removal
- DOM Replacement
- General Attributes
- Style Properties
- Collection Manipulation
- Data Storage
- DOM Element Methods
- Setup Methods
- Properties of jQuery Object Instances
- Properties of the Global jQuery Object
- Attribute
- Basic
- Basic Filter
- Child Filter
- Content Filter
- Form
- Hierarchy
- jQuery Extensions
- Visibility Filter
- Filtering
- Miscellaneous Traversing
- Tree Traversal
- Version 1.0
- Version 1.0.4
- Version 1.1
- Version 1.1.2
- Version 1.1.3
- Version 1.1.4
- Version 1.2
- Version 1.2.3
- Version 1.2.6
- Version 1.3
- Version 1.4
- Version 1.4.1
- Version 1.4.2
- Version 1.4.3
- Version 1.4.4
- Version 1.5
- Version 1.5.1
- Version 1.6
- Version 1.7
- Version 1.8
- Version 1.9
- Version 1.11 & 2.1
- Version 1.12 & 2.2
- Version 3.0
- Version 3.1
- Version 3.2
- Version 3.3
- Version 3.4
- Version 3.5
- Version 3.6
- Version 3.7
Books
Copyright 2023 OpenJS Foundation and jQuery contributors. All rights reserved. See jQuery License for more information. The OpenJS Foundation has registered trademarks and uses trademarks. For a list of trademarks of the OpenJS Foundation, please see our Trademark Policy and Trademark List. Trademarks and logos not indicated on the list of OpenJS Foundation trademarks are trademarks™ or registered® trademarks of their respective holders. Use of them does not imply any affiliation with or endorsement by them. OpenJS Foundation Terms of Use, Privacy, and Cookie Policies also apply. Web hosting by Digital Ocean | CDN by StackPath
Replace text with jQuery [with examples]
To replace the text of any element using jQuery use the text function together with the replace function of JavaScript. For example: $(«#element»).text($(«#element»).text().replace(«Hi», «Bye»)); .
Here’s the step by step process:
- Find and select the element containing the text.
- Use the jQuery text function to get its text.
- Replace the text using replace .
- Pass the result of this process to the text function to the same element.
The replace() admits two parameters. The first is the value we want to replace (or the regular expression) and the second is the new string that will replace it. It returns the new generated string.
Let’s say we have a string saying «Hi Paul» and we want to replace it for «Bye Paul».
We can do it all in a single line like this:
// Assuming #element is the ID of the element containing
// the text to be replaced
$("#element").text($("#element").text().replace("Hi", "Bye"));If that looks a bit confusing to you, we can split it in multiple lines to make it easier to read:
// Same as above, but spread in multiple lines
const element = $("#element");
const textToReplace = element.text();
const newText = textToReplace.replace("Hi", "Bye");
element.text(newText);Easy right? Now, what if you want to change the text when clicking on a button? Or perhaps you want to replace multiple paragraphs?
Here’s a list of the most common scenarios for text replacement. All of them using jQuery:
Examples replacing strings in jQuery:
Replace the text of an element on click:
const changeText = (e) =>
// Multiple lines solution
const element = $("#element");
const textToReplace = element.text();
const newText = textToReplace.replace("Hi", "Bye");
element.text(newText);
>;
// Attaching the click event on the button
$(document).on('click', '#changeText', changeText);Replace multiple appearances of the same string
In order to replace all appearances of a string we have to use regular expressions. Instead of using this:
textToReplace.replace("Hi", "Bye");
We have to use the following:
textToReplace.replace(/Hi/g, "Bye");
Notice we also removed the double quotes around «Hi» and we added the global flag g after the last / . This is what allows us to search globally, or in other words, to look for all appearances for the searched string.
// Replaces all appearances of "Hi" for "Bye"
var element = $("#element");
element.text(element.text().replace(/Hi/g, "Bye"));Replace multiple words at the same time
We’ll have to use a regular expression as we did above, but this time, to add multiple words, we will separate them by | .
// Replaces the words "Hi", "Hello" and "Hey" for "Bye"
element.text(element.text().replace(/Hi|Hello|Hey/g, "Bye"));Replace case-insensitive text
This applies when you want to replace a string no matter if it appears in uppercases, lowercases or a combination of both.
Again, we’ll have to use regular expressions for it. We’ll make use of the i flag that we’ll pass after the last / , together with the g that allows for a global search as mentioned before:
// Replacing "Hi" and "hi" for "Bye"
element.text(element.text().replace(/hi/gi, "Bye"));Replace a word in multiple texts
Let’s imagine we want to replace a word in multiple elements in our website. All we have to do is iterate over them and call our function or just call the function multiple times on each of them:
Remove text using replace
Of course, you can use this same method to replace any text for an empty string removing the searched string from our text.
// Removing word from a string using jQuery
var element = $("#element");
element.text(element.text().replace("Hi", ""));Replace a whole text, word, or sentence
We can replace the whole text of any element on our page by using the text function of jQuery. It’s even more simple yet:
Replace HTML string with jQuery
In a similar way, we can replace the whole HTML content by using the html function:
$("#element").html("This is my italic text");
Conlusion
By using jQuery in combination of JavaScript functions we are able to replace strings in elements, texts and even JavaScript variables.
Unlike in other languages, in JavaScript the replacement of multiple appearances forces us to use regular expressions. This can be a bit more scary at first and once you know the basis it opens a whole new world of opportunities for us.
I hope this articles serves as a way to clarify the different ways we can use jQuery to replace strings and texts on your site.
If you are learning JavaScript check out what’s the best way to learn JavaScript!
Related articles