Home > Net >  JS - Nested i before h1 text
JS - Nested i before h1 text

Time:12-14

I need to dinamically change this code:

<h1  id="title"><i ></i> Example</h1>

So, I have a JS function where I do:

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

the problem is that the result is:

<h1  id="title"> hello<i ></i></h1>

instead of:

<h1  id="title"><i ></i> hello</h1>

So, how can I put the h1 text content before the i?

CodePudding user response:

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

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

console.log(h1Title);

result will be like this in console :

<h1  id="title"><i </i>Hello</h1>

CodePudding user response:

instead of append in h1Title use prepend on iTitle.

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  id="title">
  <i ></i> Example
</h1>

  • Related