Domanda

I used to use document.write() instead of using document.getElementById(), when I used document.write() I could openly use document.open() which meant that I could have different pages but still staying on the same page (.html). I've tried many things such as hiding the elements but that makes the links on them still clickable.

I would like the achieve the same things but while still using good practise.

Here is what I used to do;

document.write("Hey!");
document.write('<button onclick="bye()">');

function bye() {
    document.open()
    // Clears page
    document.write("Bye");
}
È stato utile?

Soluzione

If you are asking how to append elements and remove them from a page without having to use document.write, you can do so using document.createElement()

Consider this example:

The add button will create a div and then append it to another div in the page called target. remove will remove the first child element of the target div.

<!DOCTYPE html>
<html>
   <head>
      <title>Div Controller</title>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width">
      <script>
         function main() {
            document.getElementById("add").addEventListener("click", function() {
               var newDiv = document.createElement("div");
               newDiv.innerHTML = "I'm a div";
               document.getElementById("target").appendChild(newDiv);
            });
            document.getElementById("remove").addEventListener("click", function() {
               var target = document.getElementById("target");
               if (target.firstChild) {
                  target.removeChild(target.firstChild);
               }
            });
         }

         window.onload = main;
      </script>
   </head>
   <body>
      <div id="target"></div>
      <button id="add">Add</button>
      <button id="remove">Remove</button>
   </body>
</html>

Altri suggerimenti

Don't use document.write(). Instead, I'd just use document.body.innerHTML to "", and append things to the innerHTML, like this

function bye(){
     document.body.innerHTML=""; //clears page
     document.body.innerHTML+="Bye";
}

or you could combine the two into

document.body.innerHTML="Bye";
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top