如何使用javascript隐藏子元素

时间:2014-01-24 11:06:44

标签: javascript

<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 个答案:

答案 0 :(得分:4)

请改为尝试:

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


编辑:上面只会隐藏一个元素,因为您的文本元素不包含在特定元素中,因此它变得更加棘手。如果您乐意“删除”您不想要的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

答案 1 :(得分:0)

如果您不需要其余的,请插入新的HTML

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

答案 2 :(得分:0)

    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';