DEV Community


Posted on


A button generates a button

You know a button with onclick, something happens when you click the button.
It may be too easy for you to display sentences or comments or explanations when you click the button.
Well, how about a button? I mean, have you ever imagined to display another button with onclick when you click the button?

The simplest way to realise it is to call the style of CSS.

For the button with id="btn" and onclick="showbtn()" and another button with initially display: "none" in CSS, it is

function showbtn(){
  document.getElementById("btn").style.display = "block";

Then another button appears when you click the button. Of course another button can also be endowed with onclick if you want.

However, there is a sophisticated way to do the same thing. The magic word is "innerHTML."
innerHTML rewrites an element in HTML as HTML. Actually, "as HTML" is so much important.
It is too easy to rewrite a paragraph. For example, <p id="lorem">Lorem ipsum...</p> is easily rewritten by

document.getElementById("lorem").innerHTML = "Lorem ipsum dolor sit amet...";

"as HTML" means that you can write HTML elements inside the double quotations!
For example,

document.getElementById("lorem").innerHTML = 'Lorem ipsum dolor sit amet, <button id="next" onclick="next()">Next</button>';          

It is just like a single page application. Note that the double quotations were replaced with single quotations actually.
If innerHTML, you can add any HTML element anytime.
Give it a shot and safe journey!

Top comments (0)