Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/89.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如果不包含子元素,则隐藏父元素-Javascript_Javascript_Html - Fatal编程技术网

如果不包含子元素,则隐藏父元素-Javascript

如果不包含子元素,则隐藏父元素-Javascript,javascript,html,Javascript,Html,如果父元素的子元素不包含内容,我想隐藏父元素 它没有给我任何错误,但它根本不起作用 我的代码是 函数元素(子元素、父元素){ 如果(!child.length){ parent.classList.add('hidden'); } } 函数hideGallery(){ var child=document.querySelectorAll('.test'), 父项=document.querySelectorAll('.row'); 如果(父项===null){ 返回; } hasElemen

如果父元素的子元素不包含内容,我想隐藏父元素

它没有给我任何错误,但它根本不起作用

我的代码是

函数元素(子元素、父元素){
如果(!child.length){
parent.classList.add('hidden');
}
}
函数hideGallery(){
var child=document.querySelectorAll('.test'),
父项=document.querySelectorAll('.row');
如果(父项===null){
返回;
}
hasElement(子元素、父元素);
}
hideGallery()
.hidden{display:none}
.测试{高度:100px;宽度:100px;背景色:红色}

img
尝试使用CSS伪类

注意:它不适用于空白

if(document.querySelectorAll('.col:empty').length){
document.querySelectorAll('.row')[0]。classList.add('hidden'))
}
.test:空{
显示:无;
}
.隐藏{
显示:无
}


您的子变量和父变量是数组。您可以使用
document.querySelector()
document.queryselectoral()[0]
来解决此问题。

一种简单的方法是通过父循环并直接检查循环中的子循环。如果子类的长度为0,则添加隐藏类

function hideEmptyParents(){
  const parent = document.querySelectorAll('.row');
  parent.forEach(p => {
    const children = p.querySelectorAll('.col');
    if(children.length == 0) p.classList.add('hidden');
  })
}

我为您制作了一个代码段-如果不包含文本或图像,请将其制作为“是”
parent=document.queryselectoral('.row')是节点列表。您需要使用querySelector或loop
querySelectorAll
返回它没有的节点列表(可能有许多元素)
classList
您需要循环项。
.hidden[display:none}
这是什么?不会隐藏父节点列表