Jovan Angelov Jovan Angelov - 1 month ago 6
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('https://www.google.com/');
ss.appendChild(text);
document.getElementById('water').appendChild(ss);
}
function ff() {
var s = document.createElement('a');
var t = document.createTextNode("https://www.google.com/");
s.appendChild(t);
s.href = "http://example.com";
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>
</body>


And I get this when I click the button http://prntscr.com/d0b95v

Answer

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);
Comments