html JS -h1文本前嵌套i

z4bn682m  于 2022-12-16  发布在  其他
关注(0)|答案(2)|浏览(134)

我需要动态地更改此代码:

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

所以,我有一个JS函数,我做:

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

问题是结果是:

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

而不是:

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

那么,如何将h1文本内容放在i之前呢?

4xrmg8kj

4xrmg8kj1#

let h1Title = document.getElementById("title");

let iTitle = document.createElement("i");
iTitle.classList.add("fas", "fa-fw", "fa-bullhorn");
h1Title.prepend(iTitle);

console.log(h1Title);

在控制台中的结果如下所示:

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

r6vfmomb2#

在iTitle上使用prepend代替h1Title中append

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

console.log(h1Title)
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" rel="stylesheet" />
<h1 class="h3 mb-0 text-gray-800" id="title">
  <i class="fas fa-fw fa-bullhorn"></i> Example
</h1>

相关问题