开发者问题收集

如何使用 JS 隐藏父级的子元素?(或 Jquery)

2022-04-26
74

我想使用 JS 或 JQuery 隐藏 <div id='altOcr'> 中的 <div id='coco'>

这是我的基本代码:

<div id='altOcr'>
    <div id='coco'>abc</div>
    <div id='coco'>def</div>
</div>
<div id='altOcr'>
    <div id='coco'>abc</div>
    <div id='coco'>def</div>
</div>

我浏览了一下论坛,测试解决方案,但对我来说不起作用。至少我无法隐藏选定的元素。

document.getElementById('coco').altOcrNone.style.display='none';

但此代码给我一个错误:

Uncaught TypeError: Cannot read properties of undefined (reading 'style')

2个回答
// select all alt0cr divs

const allaltOcr = document.querySelectorAll("#altOcr");


// looping through each div and selecting children to set siplay property. It is not very efficent, but might work for you!

allaltOcr.forEach((e) => {
  const children = e.querySelectorAll("#coco");
  children.forEach(e => { 
   e.style = "display: none"
  })
});
<div id='altOcr'>
    <div id='coco'>abc</div>
    <div id='coco'>def</div>
</div>
<div id='altOcr'>
    <div id='coco'>abc</div>
    <div id='coco'>def</div>
</div>
<div id='coco'>STILL HERE :)</div>
ACCode
2022-04-26

var hideElement = document.getElementById('coco');

hideElement.style.display='none';

Ehsan
2022-04-26