DEV Community

safejourney-art
safejourney-art

Posted on

1

A button generates a button

Hello!
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)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay