How to exchange content from a div using javascript?

Asked

Viewed 739 times

1

I am trying to create a script to replace everything inside a div with something predefined, I am new in javascript and I am working to find a solution for this, I searched in several places, but I did not get anything.

I’m calling the script using url.searchParams.get

if(url.searchParams.get("sub") == 1) {
    document.getElementById("rep").innerHTML = "<p>Outro texto</p>"
}
<div id="rep">Texto</div>
  • Vc created the URL object?

  • What would be url.searchParams.get?

1 answer

0


The searchParams is a property of the object URL. Therefore, to use it you must first create the object with a valid URL. If you want to use the current URL of the page in the object, just use the property as parameter location.href:

let url = new URL(location.href);

With the object created in the variable url, you can access the property url.searchParams using get():

let url = new URL(location.href);
if(url.searchParams.get("sub") == 1) {
    document.getElementById("rep").innerHTML = "<p>Outro texto</p>"
}

If the page URL contains a value sub=1, the if will be accessed and the HTML of div will be replaced.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.