简体   繁体   中英

Create an array of a parents children in javascript

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM