Write html with Javascript

0

I have a web page, which I want when I click on a button to activate an html code (I mean more buttons) to make a menu. How can I do that? I have this, but when I click the button, it deletes the whole page and puts only the button that I activate. (It's an example of what I have)

<button onclick=“activar” value=“menu” type=“submit”>
</button>

<script>
function activar(){
Document.write(“<div><button id=‘b1’></button></div>”);
}
    
asked by Juan Vial 04.10.2018 в 15:20
source

2 answers

1

You delete all the content because the button is submit type and when you put it in that way, restart the whole screen as if you were giving it a F5 ; here I put 2 examples you remove the submit and in the onclick event you should call the function with its parentheses so onclick="activar()" :

In this example you simply create the button anywhere in the body :

function activar(){
  document.body.innerHTML += "<div><button id='b1'>Nuevo Botón</button></div>";
}
<button onclick="activar()" value="menu">Activar</button>

and with this you create the button in a specific element as a div with an id:

function activar(){
      let div = document.getElementById("nuevo_boton");
      div.innerHTML = "<div><button id='b1'>Nuevo Botón</button></div>";
    }
#nuevo_boton{
  border:1px solid red;
}
<button onclick="activar()" value="menu">Activar</button>
<div id="nuevo_boton"></div>
    
answered by 04.10.2018 / 22:18
source
5

You can use the innerHTML method to render html tags in the DOM

document.getElementById("container").innerHTML = "<img src='https://cdn-images-1.medium.com/max/2000/1*6ahbWjp_g9hqhaTDSJOL1Q.png" />'
<div id='container'></div>
    
answered by 04.10.2018 в 15:36