【问题标题】:Clearing div child elements without removing from the DOM清除 div 子元素而不从 DOM 中删除
【发布时间】:2021-12-05 02:55:09
【问题描述】:
我的目标是,使用 Jquery 或 vanilla JS,清除 div 及其每个子元素的内部文本,同时在事后保持所有元素完好无损。在下面的示例中,div 是student_profile。
关于 SO 的答案推荐了函数 .html('') 和 .text(''),但是,如下面的示例所示,这完全从 DOM 中删除了子元素(我的示例仅显示了一个函数,但实际上都删除了该元素)。是否有一个函数可以删除当前 div 和子 div 中的所有文本,同时保持元素本身完好无损?
如有任何建议,我们将不胜感激!
function cleardiv() {
console.log(document.getElementById("student_name"));
$('#student_profile').html('');
console.log(document.getElementById("student_name"));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='student_profile'>
<h1 id="student_name">Foo Bar</h1>
<p id="student_id">123</p>
<p id="studen_course">math</p>
<p id="last_reported">2021-01-01</p>
</div>
<button onclick="cleardiv()">Clear</button>
【问题讨论】:
标签:
javascript
html
jquery
dom
【解决方案1】:
一种选择是select all text node descendants 和.remove() 他们,保持实际元素不变:
const getTextDecendants = (parent) => {
const walker = document.createTreeWalker(
parent,
NodeFilter.SHOW_TEXT,
null,
false
);
const nodes = [];
let node;
while (node = walker.nextNode()) {
nodes.push(node);
}
return nodes;
}
function cleardiv() {
for (const child of getTextDecendants($('#student_profile')[0])) {
child.remove();
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='student_profile'>
<h1 id="student_name">Foo Bar</h1>
<p id="student_id">123</p>
<p id="studen_course">math</p>
<p id="last_reported">2021-01-01</p>
</div>
<button onclick="cleardiv()">Clear</button>
【解决方案2】:
您可以尝试使用选择器#student_profile * 来包含所有子元素。
function cleardiv() {
console.log(document.getElementById("student_name"));
$('#student_profile *').text('');
console.log(document.getElementById("student_name"));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='student_profile'>
<h1 id="student_name">Foo Bar</h1>
<p id="student_id">123</p>
<p id="studen_course">math</p>
<p id="last_reported">2021-01-01</p>
</div>
<button onclick="cleardiv()">Clear</button>
【解决方案3】:
如果您只想影响直接子元素,则可以迭代父元素的childNodes。这将清除元素节点以及非元素节点,例如文本节点。这里使用返回的NodeList提供的NodeList#forEach()方法。
function cleardiv() {
document.getElementById('student_profile')
.childNodes
.forEach((node) => (node.textContent = ''));
console.log(document.getElementById('student_name'));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='student_profile'>
<h1 id="student_name">Foo Bar</h1>
<p id="student_id">123</p>
<p id="studen_course">math</p>
<p id="last_reported">2021-01-01</p>
</div>
<button onclick="cleardiv()">Clear</button>