I want to change anything that says "Contact Me" to "Contact Us". I found some examples online they require either finding the ElementID or etc. I’m stumped on how I can achieve these. Can someone point me in the right direction?
I found examples like the below that use the ElementID but I can’t find such thing for the button.
let text = document.getElementById("demo").innerHTML;
document.getElementById("demo").innerHTML = text.replace("Microsoft", "W3Schools");
I looked at trying to use an example like following, but I think its just completely wrong.
let originalString = "Contact Me";
let newString = originalString
.replace("Contact Me", "Contact Us");
console.log(newString);
Any advice would be great. Thanks.
4
Answers
You should just search and replace the text in the IDE or text editor. You should not need to do this via Javascript at all. Search for the phrase "Contact Me" in your text editor. Before replacing it, make sure it wrapped in either button tags to link tags i.e.
OR
I see your web using wordpress, maybe it use some contact plugin and its better to change in wordpress instead modify with script. But, you can try this code for this moment:
So we first define two constants
searchString
andreplacementString
.searchString
contains the text we want to find in the document(Contact Me), andreplacementString
contains the text we want to replace it with(Contact Us).The function
replaceText()
will recursively traverse through the DOM to find text nodes and input elements. This is what it does:checks if the passed node is a text node or an element node
if it’s a text node, it converts both the search string and the node content to lowercase for case-insensitive comparison
it checks if the lowercase node content contains the lowercase search string
if it does contain the search string, it replaces the text while preserving the original case
if it is an element node, it checks if the element is an
<input>
element and if its value matches the search stringif it does match the search string, it replaces the input value with the replacement string
after processing the current node, it recursively calls itself for each child node of the current node
it starts the process by calling
replaceText()
withdocument.body
as the initial node, which initiates the traversal of the entire document body so it covers the entire HTML pageDon’t really know why you would want to do it this way but, the key is to use a regex to find all variations you want to change.