javascript 如何使用javascript隐藏子元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21331067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 20:39:49  来源:igfitidea点击:

How to hide child elements using javascript

javascript

提问by Prashobh

<div id="wpq2">
   <div class="subClass">
   <a id="linkTO" class="subClass">New Item</a>
   or
   <a class="subClass">edit</a>
   this list
   </div>
</div>

i want to hide all the thing except

我想隐藏所有的东西,除了

   <a id="linkTO" class="subClass">New Item</a>

I do not have access to html , i have to use javascript

我没有访问 html 的权限,我必须使用 javascript

i tried somthing

我试过了

var parentID = document.getElementById('wpq2');
var sub = parentID.getElementsByClassName('subClass');
var lastChild = sub[0].lastChild;
lastChild.style.display = 'none';

Using javascript no idea how to do

使用javascript不知道该怎么做

Please suggest

请建议

回答by musefan

Try this instead:

试试这个:

var parentID = document.getElementById('wpq2');
//get the first inner DIV which contains all the a elements
var innerDiv = parentID.getElementsByClassName('subClass')[0];
//get all the a elements
var subs = innerDiv.getElementsByClassName('subClass');

//This will hide all matching elements except the first one
for(var i = 1; i < subs.length; i++){
   var a = subs[i];
   a.style.display = 'none';
}

Here is a working example

这是一个工作示例



EDIT: The above will only hide the a element, as your text elements are not contained within specific elements then it becomes more tricky. If you are happy to effectively "delete" the HTML you don't want then you can do the following:

编辑:以上只会隐藏 a 元素,因为您的文本元素不包含在特定元素中,那么它会变得更加棘手。如果您乐于有效地“删除”您不想要的 HTML,那么您可以执行以下操作:

var parentID = document.getElementById('wpq2');
//get the first inner DIV which contains all the a elements
var innerDiv = parentID.getElementsByClassName('subClass')[0];
//get the HTML for the a element to keep
var a = innerDiv.getElementsByClassName('subClass')[0].outerHTML;
//replace the HTML contents of the inner DIV with the element to keep
innerDiv.innerHTML = a;

Here is an example

这是一个例子

回答by Trupti

    var parentID = document.getElementById('wpq2');
    var innerDiv = parentID.getElementsByClassName('subClass')[0];
    var subs = innerDiv.getElementsByClassName('subClass');
    subs.forEach(function (sub) { sub.style.display = 'none'; });
    document.getElementById("linkTO").style.display = 'block';

回答by Pal Singh

insert new html if you don't need the rest

如果您不需要其余部分,请插入新的 html

document.getElementById('wpq2').innerHTML = '<a id="linkTO" class="subClass">New Item</a>';