簡體   English   中英

JS - 在 h1 文本之前嵌套 i

[英]JS - Nested i before h1 text

我需要動態更改此代碼:

<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 之前呢?

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>

而不是在 h1Title 中追加,而是在 iTitle 上使用prepend

 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>

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM