为何添加类的DOM元素追加文本后样式不生效?附代码示例
问题描述
第一个示例中,执行helloWorldPara1.textContent += 'world';追加文本时,之前通过hello.classList.add('red')添加的red类并未生效。如果注释掉这行代码,“hello”就会显示为红色。
第二个示例中,最后添加带样式的元素,样式能正常工作。
为什么先添加带类的元素,再追加额外文本会失效?
相关代码
CSS
.red{ color: red; }
HTML
<div id="helloWorld1"></div> <div id="helloWorld2"></div>
JavaScript
// 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);
原因分析
问题出在textContent的工作机制上:当你给元素设置textContent(包括+=这种追加操作)时,它会清空元素内所有现有的子节点(包括你之前添加的<span>元素),然后把新的文本内容作为纯文本节点插入进去。
在第一个示例中,你先把带red类的<span>添加到<p>里,然后执行helloWorldPara1.textContent += 'world',这一步相当于:
- 清空
<p>里的<span>节点 - 把原来的文本内容(
hello)加上world合并成纯文本hello world,作为新的文本节点插入<p>中
原来的<span>被删除了,自然red类的样式也就消失了。
第二个示例之所以正常,是因为你先给<p>设置文本,再添加<span>节点——这时候textContent操作在前,不会影响后续添加的子元素。
解决方案
如果要保留原来的子元素同时追加内容,不要用textContent,而是创建新的文本节点或者用append()方法添加:
修正后的第一个示例代码
// 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); // 改用创建文本节点并追加,保留原有span helloWorldPara1.appendChild(document.createTextNode('world')); // Append p to html div helloWorld1.appendChild(helloWorldPara1);
或者用更简洁的append()方法(支持直接传入字符串):
helloWorldPara1.append('world');
append()方法可以接受字符串、文本节点或元素节点,不会清空现有子元素,只是在末尾添加内容。
内容的提问来源于stack exchange,提问作者JAmes
相关产品推荐
相关产品推荐

