1

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>
1
  • 1
    1. inside the click listener, you can use this to get the button 2. simply use node.remove() Commented May 3, 2022 at 10:25

3 Answers 3

2

Replacing this.outerHTML also works and keeps it simple:

<button onclick="this.outerHTML='<p>some text</p>'">Click</button>

Sign up to request clarification or add additional context in comments.

1 Comment

I also like potatoes 😊
0

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>

Comments

0
function ReplaceButton() {
    // Get the button
    node = document.getElementById("MyButton");
    // Add some HTML after the button (in the buttons parent)
    node.insertAdjacentHTML("afterend", "<p>Some text</p>");
    // Hide the button, optionally remove from tree with `node.remove()`
    node.style.display = "none";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.