You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS动态修改DOM:如何让<i>元素置于<h1>文本内容之前?

问题:调整DOM元素顺序使图标位于文本之前

原始DOM结构

<h1 class="h3 mb-0 text-gray-800" id="title"><i class="fas fa-fw fa-bullhorn"></i> Example</h1>

当前执行的JavaScript代码

h1Title = document.getElementById('title');
iTitle = document.createElement('i');
iTitle.classList.add("fas");
iTitle.classList.add("fa-fw");
iTitle.classList.add("fa-bullhorn");
h1Title.textContent = ' hello';
h1Title.appendChild(iTitle);

当前生成的DOM结果

<h1 class="h3 mb-0 text-gray-800" id="title"> hello<i class="fas fa-fw fa-bullhorn"></i></h1>

预期DOM结果

<h1 class="h3 mb-0 text-gray-800" id="title"><i class="fas fa-fw fa-bullhorn"></i> hello</h1>

修正方案

方法1:使用insertBefore插入到文本节点前

h1Title = document.getElementById('title');
iTitle = document.createElement('i');
iTitle.classList.add("fas");
iTitle.classList.add("fa-fw");
iTitle.classList.add("fa-bullhorn");
h1Title.textContent = ' hello';
// 将i元素插入到h1的第一个子节点(即文本节点)之前
h1Title.insertBefore(iTitle, h1Title.firstChild);

方法2:先添加图标,再追加文本节点

h1Title = document.getElementById('title');
iTitle = document.createElement('i');
iTitle.classList.add("fas");
iTitle.classList.add("fa-fw");
iTitle.classList.add("fa-bullhorn");
// 清空h1原有内容
h1Title.innerHTML = '';
// 先添加图标元素
h1Title.appendChild(iTitle);
// 创建文本节点并添加到h1中
const textNode = document.createTextNode(' hello');
h1Title.appendChild(textNode);

方法3:使用prepend直接前置图标(现代浏览器支持)

h1Title = document.getElementById('title');
iTitle = document.createElement('i');
iTitle.classList.add("fas");
iTitle.classList.add("fa-fw");
iTitle.classList.add("fa-bullhorn");
h1Title.textContent = ' hello';
// 将i元素添加到h1内容的最前面
h1Title.prepend(iTitle);

原因说明

原代码中h1Title.textContent = ' hello'会清空h1内所有原有内容并添加文本,随后appendChild会把i元素追加到h1内容的末尾,导致文本在前、图标在后。通过调整i元素的插入位置,就能实现图标在前、文本在后的预期效果。

内容的提问来源于stack exchange,提问作者Andry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 22:30:42