2
<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

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

Please suggest

Prashobh
  • 9,216
  • 15
  • 61
  • 91

3 Answers3

5

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:

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

musefan
  • 47,875
  • 21
  • 135
  • 185
1

insert new html if you don't need the rest

document.getElementById('wpq2').innerHTML = '<a id="linkTO" class="subClass">New Item</a>';
Pal Singh
  • 1,964
  • 1
  • 14
  • 29
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';
Trupti
  • 108
  • 2
  • 14
  • Who said what? Where?? Please don't reference comments as a part of your solution, especially when they are on other answers. They can easily be deleted – musefan Jan 24 '14 at 11:35
  • 1
    Sorry, just updated my answer. I'm still a newbie to Stack Overflow ethics, thanks for your advice. – Trupti Jan 24 '14 at 11:50
  • @prash: Even if the `forEach` worked, it would have the same problem with text nodes as my original answer (pre-update) – musefan Jan 24 '14 at 12:22
  • 1
    @Trupti: The `forEach` won't work in this instance due to `subs` being a `nodeList` not an `Array`, [see here for more information](http://stackoverflow.com/a/3871602/838807) – musefan Jan 24 '14 at 12:24