Jovan Angelov Jovan Angelov - 1 year ago 109
Javascript Question

Replacing span tag with anchor tag using replaceChild javascript

I need to replace the span with id='water' with an anchor when the button is clicked using replaceChild in js. fff() works fine, so does ff() until the last two rows where i think the problem is. (I cant figure out how replaceChild works).

function fff() {
var ss = document.createElement('span');
var text = document.createTextNode('');
function ff() {
var s = document.createElement('a');
var t = document.createTextNode("");
s.href = "";
var item = document.getElementById('water');
item.replaceChild(s, item);

<body onload="fff()">
<span id="water"></span> <br><br>
<button onclick="ff()">Replace with anchor</button>

And I get this when I click the button

Answer Source

Element.replaceChild is used to replace a child of Element by another element. Since you want to replace the span#water, you have to select its parent (which is <body>) and call replaceChild. You might change your last line of ff to this

var body = document.body;
body.replaceChild(s, item);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download