0

I am learning HTML and Javascript, and for an assignment I need to get a button to change an element to another HTML file.

Here is my code:

main.html

</head>
    <script src="testscript.js"></script>
</head>

<body>
    <button onclick="button1()">Function 1</button>
</body>

testscript.js

function button1(){
var value = confirm("Press anything");

if(value == 1){
    document.getElementById("abc").innerHTML = "Ok";
    window.location.assign("button1.html");}   
}

button1.html

<body>  
    <p id="abc"></p>
</body>

So basically, button1() gets called from main.html and needs to change the value of an element in button1.html.

A similar example is illustrated here: (link). I have also tried outerHTML but it doesn't work either. Is this not possible? I can't find anything online.

Note: My html and js files have to be separated.

Any help is appreciated. Thanks.

1 Answers1

3

First: Inline event handling is not a best practice; instead give your button an ID and attach an event handler to it.

Second: Any DOM manipulations should be handled after the DOM has loaded; either move your JS to the bottom just before the closing body tag, or use window.onload.

So, if you have the following HTML:

<button id="f1">Function1</button>

...then, you should have something like this in your JS file:

window.onload = function() {
    document.getElementById('f1').onclick = function() {
    var value = prompt("Press anything");
    };
};

To pass data between pages you can use cookies, localStorage or URL query parameters.

Community
  • 1
  • 1
lindynetech
  • 81
  • 1
  • 5