<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不知道该怎么办

请建议

最佳答案

尝试以下方法:

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

10-07 19:56
查看更多