RemoveChild 和appendChild 元素未被删除或追加

问题描述 投票:0回答:1

当我查看控制台时,这个脚本正在运行,但不会影响页面。

accountLink
未删除,且
userIcon
未替换它。

我预计 accountLink 会被删除并且 userIcon 会出现。

window.onload = function() {
  const userIcon = document.createElement('i');
  const accountLink = document.getElementById('account-link');
  const accountWrap = document.getElementById('account-link-wrap');
  userIcon.className = "fa-light fa-user";
  accountWrap.removeChild(accountLink);
  accountWrap.appendChild(userIcon);
  console.log(userIcon);
}
<!-- HTML here, please -->

javascript dom-manipulation
1个回答
0
投票

我用一些示例 HTML 准确测试了您的代码,它可以工作,请参阅示例。也许你的 HTML 部分是错误的。

    window.onload = function() {
        const userIcon = document.createElement('i');
        const accountLink = document.getElementById('account-link');
        const accountWrap = document.getElementById('account-link-wrap');
        userIcon.className = "fa-light fa-user";
        accountWrap.removeChild(accountLink);
        accountWrap.appendChild(userIcon);
        console.log(userIcon);
    }
<div id="account-link-wrap">
  <div id="account-link">
    Account Link
  </div>
</div>

© www.soinside.com 2019 - 2024. All rights reserved.