I want to replace an element by another. The element however is placed in an div with other elements. When I run my code the whole div is replaced. How do I prevent this behavior?
function edit(e) {
selectedElement = e.id
var newElement = document.createElement("input");
var newElementA = document.createTextNode("bla");
newElement.appendChild(newElementA);
var oldElement = document.getElementById(selectedElement);
var parentDiv = oldElement.parentNode
parentDiv.replaceChild(newElement, oldElement);
}
You shouldn't be appending a text node to an input box. You should set the value.
Here is a working codepen, based on your comments.
<div id="parentDiv">
<div>
hi
</div>
<a id="pleaseReplace" onclick="edit(event)">hi2</a>
<div>
hi3
</div>
</div>
function edit(e) {
selectedElement = document.getElementById(e.srcElement.id);
var newElement = document.createElement("input");
newElement.value = selectedElement.innerHTML;
var parentDiv = selectedElement.parentNode
selectedElement = parentDiv.replaceChild(newElement, selectedElement);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.