如何使用 javascript 隐藏子元素
2014-01-24
25673
<div id="wpq2">
<div class="subClass">
<a id="linkTO" class="subClass">New Item</a>
or
<a class="subClass">edit</a>
this list
</div>
</div>
我想隐藏除
<a id="linkTO" class="subClass">New Item</a>
我无法访问 html, 我必须使用 javascript
我试过一些东西
var parentID = document.getElementById('wpq2');
var sub = parentID.getElementsByClassName('subClass');
var lastChild = sub[0].lastChild;
lastChild.style.display = 'none';
使用 javascript 不知道怎么做
请提出建议
3个回答
请尝试以下方法:
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';
}
编辑 :以上方法只会隐藏 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;
musefan
2014-01-24
如果不需要其余部分,请插入新的 html
document.getElementById('wpq2').innerHTML = '<a id="linkTO" class="subClass">New Item</a>';
Pal Singh
2014-01-24
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';
Trupti
2014-01-24