简体   繁体   中英

How can I insert a span tag inside of a dynamically created element?

So I have this html code i'm trying to replicate using dom manipulation

<h1 id="intro-text">
    HAMADILYTICAL<span id="word">Grill</span>
</h1> 

I have some styling for that specific span so that it doesn't render in the same line. This is what I tried but it's obviously not going to work because I'm appending the child after that node not inside of it.

// main content
const mainContent = document.createElement('div');
const introText = document.createElement('h1');
const span = document.createElement('span');
mainContent.className = 'main-content';
introText.id = 'intro-text';
span.id = 'word';
introText.textContent = `HAMADILYTICAL Grill`;
content.appendChild(mainContent);
mainContent.appendChild(introText);
introText.appendChild(span);

using innerHTML fixed it

const mainContent = document.createElement('div');
const introText = document.createElement('h1');
mainContent.className = 'main-content';
introText.id = 'intro-text';
introText.innerHTML = `<h1 id="intro-text">
HAMADILYTICAL <span id="word">Grill</span></h1>`;
content.appendChild(mainContent);
mainContent.appendChild(introText);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM