Thomas
Thomas

Reputation: 43

onClick replace javascript element, with new javascript element

What I am trying to figure out is how to make a button, that when you click, will replace itself with a textbox. I found this code on the W3Schools website, and can't figure out how to put javascript (or HTML) elements in.

<p>Click the button to replace "Microsoft" with "W3Schools" in the paragraph below:</p>

<p id="demo">Visit Microsoft!</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    var str = document.getElementById("demo").innerHTML; 
    var res = str.replace("Microsoft", "W3Schools");
    document.getElementById("demo").innerHTML = res;
}
</script>

</body>
</html>
<input type="text" name="textbox" value="textbox"><br>

In the end I want to be able to replace a button with the textbox I put outside the html tags

Upvotes: 2

Views: 4055

Answers (2)

Thomas
Thomas

Reputation: 43

I ended up finding a code that works off of http://www.webdeveloper.com/forum/showthread.php?266743-Switch-Div-Content-Using-Javascript

Upvotes: -1

Luke
Luke

Reputation: 8407

I would not suggest you the innerHTML replacement method.

Here are the steps where you can use replaceChild

  1. Get the parent node of the selected element
  2. use replaceChild

Here the code

// create the new element (input)
var textBox = document.createElement("input");
textBox.type = "text";

// get the button
var button = document.getElementById("demo");
// reference to the parent node
var parent = element.parentNode;
// replace it
parent.replaceChild(textBox, button);

On older browser you probably need a slighlty different solution.

var parent = button.parentNode;
var next = button.nextSibling;
// remove the old
parent.removeChild(button);
// if it was not last element, use insertBefore
if (next) {
   parent.insertBefore(textBox, next);
} else {
   parent.appendChild(textBox);
}

Upvotes: 3

Related Questions