使用replaceChild javascript将span标签替换为锚标记

Replacing span tag with anchor tag using replaceChild javascript

本文关键字:替换 标签 replaceChild javascript span 使用      更新时间:2023-09-26

我需要在js中使用replacecchild单击按钮时,用锚替换id='water'的span。Fff()工作正常,ff()也是如此,直到最后两行,我认为问题是。(我不知道replacecchild是怎么工作的)

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>

当我点击这个按钮http://prntscr.com/d0b95v

元素。replacecchild用于用另一个元素替换Element的子元素。因为你想要替换span#water,你必须选择它的父(这是<body>)并调用replacecchild。您可以将ff的最后一行更改为

var body = document.body;
body.replaceChild(s, item);