In the first example, when I append text helloWorldPara1.textContent += 'world'; the class ('red') applied above, to hello.classList.add('red') doesn't apply. If I comment out helloWorldPara1.textContent += 'world'; I get hello in red.
In the second example, it seems to work as I applied the class last.
Why can't I append an element with a class then append extra text?
.red{
color: red;
}
<div id="helloWorld1"></div>
<div id="helloWorld2"></div>
// 1. Hello world html div
const helloWorld1 = document.getElementById('helloWorld1');
// Create p
const helloWorldPara1 = document.createElement("p");
// span - hello
const hello = document.createElement("span");
hello.classList.add('red')
hello.textContent = 'hello ';
// Append to Para
helloWorldPara1.appendChild(hello);
// Append text
helloWorldPara1.textContent += 'world'; // Commenting out applies class red to "hello"
// Append p to html div
helloWorld1.appendChild(helloWorldPara1);
// 2. Hello world html div
const helloWorld2 = document.getElementById('helloWorld2');
// Create p
const helloWorldPara2 = document.createElement("p");
// Append text
helloWorldPara2.textContent += 'hello ';
// span - world
const world = document.createElement("span");
world.classList.add('red')
world.textContent = 'world';
// Append to Para
helloWorldPara2.appendChild(world);
// Append p to html div
helloWorld2.appendChild(helloWorldPara2);