我的目標是,使用 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>
uj5u.com熱心網友回復:
一種選擇是選擇所有文本節點后代和.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>
uj5u.com熱心網友回復:
您可以嘗試使用選擇器#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>
uj5u.com熱心網友回復:
如果它只是您希望影響的直接子childNodes元素,則可以迭代父元素的 。這將清除元素節點以及非元素節點,例如文本節點。這里使用NodeList#forEach()回傳的NodeList 提供的方法。
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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/341509.html
標籤:javascript html 查询 dom
下一篇:在Regexc#中拆分字串
