如果 parentElement (h4.undefined) 中沒有文本,我需要隱藏一個圖示。有時文本可以存在,但在沒有的情況下,我需要隱藏圖示。
我這樣做的方式在瀏覽器的 console.log 中給了我一個錯誤。
什么是正確的方法?
<div class="col-auto">
<h4 class="undefined">
<i class="icon-calendar" aria-hidden="true">i</i>
<!-- some text might be possible here but sometimes it's not -->
<!-- if here is no text, hide the icon -->
</h4>
<h4 class="undefined">
undefined
</h4>
</div>
JS代碼:
let test = document.querySelectorAll('h4.undefined');
Array.from(test).forEach(i => {
if(i.textContent.includes('undefined')) {
i.style.display = 'none'; // hiding el that contains undefined text
// let inner = document.querySelectorAll('.icon-calendar');
// Array.from(inner).forEach(j =>{
// j.style.display = 'none';
// })
}
if(i.childNodes.length === 0) {
} else {
i.childNodes[1].style.display = 'none'; // error in browser's console.log - Cannot read properties of undefined (reading 'style')
}
});
uj5u.com熱心網友回復:
這是因為文本內容未定義的第二個 h4 標簽不包含任何子節點。
我希望這就是你要找的。如果是,那么您必須在第二個條件檢查中使用 else if
let test = document.querySelectorAll("h4.undefined");
Array.from(test).forEach((i) => {
if (i.textContent.includes("undefined")) {
i.style.display = "none"; // hiding el that contains undefined text
// let inner = document.querySelectorAll('.icon-calendar');
// Array.from(inner).forEach(j =>{
// j.style.display = 'none';
// })
}
// Change here
else if (i.childNodes.length === 0) {
} else {
i.childNodes[1].style.display = "none";
}
});
<div class="col-auto">
<h4 class="undefined">
<i class="icon-calendar" aria-hidden="true">i</i>
<!-- some text might be possible here but sometimes it's not -->
<!-- if here is no text, hide the icon -->
</h4>
<h4 class="undefined">undefined</h4>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/504790.html
標籤:javascript dom
