如果父元素不包含文本,则隐藏第一个元素子级



如果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')
}
});

这是因为未定义文本内容的第二个h4标记不包含任何子节点。

我希望这就是你想要的。如果是,那么你必须使用else如果在第二个条件检查

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>

最新更新