0

I am trying to create an array of a parent div's (id="lol") children and them fetch them to change display:none; except for the child with id="a". I've tried this but it doesn't work. How can I improve this to get it to work?

function myFunction() {

  var x = document.getElementById('a');

  var children = [].slice.call(document.getElementById('lol').getElementsByTagName('*'),0);
  var arrayLength = children.length;          

  for (var i = 0; i < arrayLength; i++) {
    var name = children[i].getAttribute('id');
    var z = document.getElementById(name);
    z.style.display = 'none';
  }
  x.style.display = 'block';
} 
Ouroborus
  • 16,237
  • 4
  • 39
  • 62
  • Can you be more specific about 'doesn't work' ? It looks like this code is trying to hide the id property. Do you get back the array of child divs? Would be nice to see a little more context. – Chris Sharp Apr 06 '17 at 17:44
  • 1
    Did you mean children or descendants? You say "children", but your code looks like it fetches all descendants. – Ouroborus Apr 06 '17 at 18:25

3 Answers3

3

If every child has an id attribute than it will work. Otherwise, some children might not have id attribute, in that case variable z will be undefined and accessing style property over z which is undefined will give error. Simple fix would be just handling undefined variable:

   if(z)      
       z.style.display = 'none';

Same goes with variable x, too.

Ouroborus
  • 16,237
  • 4
  • 39
  • 62
shivam Gupta
  • 441
  • 4
  • 7
0

How about using jQuery?

$('#lol').children(':not(#a)').hide();

If jQuery is not an option you can do this:

var lol = document.getElementById('lol');
var children = lol.querySelectorAll(':not(#a)');
for(var i=0;i<children.length;i++) {
    children[i].style.display = 'none';
}

Even more "low-level":

var lol = document.getElementById('lol');
var children = lol.childNodes;
for(var i=0;i<children.length;i++){
    if(children[i].id != 'a') {
        children[i].style.display = 'none';
    }
}
Max Dubinin
  • 214
  • 3
  • 20
0
function myFunction() {


  var children = [].slice.call(document.getElementById('lol').getElementsByTagName('*'),0);
  var arrayLength = children.length;          

  for (var i = 0; i < arrayLength; i++) {
   children[i].style.display = 'none';
  }
  document.getElementById('a').style.display = 'block';
} 
Aswin Ramesh
  • 1,654
  • 1
  • 13
  • 13