I would like to have a button that disappears when clicked on and replaced with something else. The code below causes the words "Some text" to appear below the button when it's clicked on. That's not quite what I want though -- how do I get "Some text" to appear in place of the button?
<button id="MyButton">Click</button>
<script>
function addListener() {
document.getElementById("MyButton").addEventListener("click", ReplaceButton, false)
}
addListener()
function ReplaceButton() {
node = document.getElementById("MyButton")
node.insertAdjacentHTML("afterend", "<p>Some text</p>")
}
</script>
CodePudding user response:
You can do something like this :
<button id="MyButton">Click</button>
<script>
document.getElementById("MyButton").addEventListener(
"click",
({ target: button }) => {
button.insertAdjacentText("afterend", "Some text");
button.remove();
},
false
);
</script>
CodePudding user response:
Replacing this.outerHTML
also works and keeps it simple:
<button onclick="this.outerHTML='<p>some text</p>'">Click</button>
CodePudding user response:
function ReplaceButton() {
node = document.getElementById("MyButton")
node.insertAdjacentHTML("afterend", "<p>Some text</p>")
node.style.display = "none"
}