Home > Net >  Text replace without reloading the page
Text replace without reloading the page

Time:12-30

I want to change the text without reloading the page.

let text = document.getElementById("main").innerHTML; 
document.getElementById("main").innerHTML = text.replaceAll("View more", "Read more");

This code works. The problem is that when there is pagination (..../shop/?page=1) on the page, it doesn't show the text change. Only when I refresh the page does the change occur. What to add to the code to make the text change happen without reloading the page?

I tried using

window.location.reload();

but it didn't help.

CodePudding user response:

One way to achieve this is by using JavaScript's history API to update the URL without reloading the page. Here's an example of how you can modify your code to do this:

let text = document.getElementById("main").innerHTML; 
document.getElementById("main").innerHTML = text.replaceAll("View more", "Read more");

// Use the history API to update the URL
history.pushState({}, '', '/shop/?page=1');

CodePudding user response:

I don't want it to update the URL.

What I meant was that if there is in the URL a /?page=1 it does not change the text

Example of:

test.com/shop - change the text "View more" to "Read more", no need to refresh

test.com/product - change the text "View more" to "Read more", no need to refresh

test.com/shop/?page=1 - no text change "View more" to "Read more", works after refresh

test.com/shop/?filters=cars - no text change "View more" to "Read more", works after refresh

  • Related