Skip to content

How to create a div on a page when clicking a button on another page

I need to write new text in a p tag on the 'cart' page when I click on the 'submit' button on the 'index' page. How can I do this with JavaScript. I have already tried with this

HTML page index :

<button onclick="myFunction()"> click me </button>

HTML page cart :

<p id="id"> </p>

Js code :

function myFunction() {
    document.getElementById('id').innerHtml = 'mytext';
}

but it does not work. How I can solve this? Thank you

Answer

index page and cart page in this reference, are different documents.

Accordingly, when you call your function on the index page, it can’t find an element with the mentioned id in that document.

function myFunction() {
    document.getElementById('id').innerHtml = 'mytext';
}

The only way to perform this trick with only Javascript, is to use Cookies. You can create a Cookie in the client’s browser and save ‘mytext’ as an object, then retrieve it on another page.

See this page https://www.w3schools.com/js/js_cookies.asp