DEV Community

Vinh Le
Vinh Le

Posted on

Reveal the nth child of a div with id ‘hello’

Hi all,
I am getting stuck on how to reveal the nth child of a div with id ‘hello’ by pure JavaScript. I actually tried:

var elements = document.getElementById(hello);
var child = elements.children[n-1];
child.style.display = block;
Enter fullscreen mode Exit fullscreen mode

However, it doesn’t seem to be right. Would be great to hear how you are likely to solve this problem! Thank you!

Top comments (3)

Collapse
 
ben profile image
Ben Halpern • Edited

The code seems correct to me, assuming n is assigned previously. Any additional context into the output might help.

Collapse
 
danielcamargo profile image
Daniel Camargo • Edited

If you want to make all the elements inside of hello visible, you need to set the style.display = block the each of them individually. You can do that by using a loop, like this example bellow:

var elements = document.getElementById('hello');
for (i=0; i<elements.children.length; i++) {
  var child = elements.children[i];
  child.style.display = 'block';
}

or if you want this the last one to be visible:

var elements = document.getElementById('hello');
elements.children[elements.children.length-1].style.display = 'block';
Collapse
 
kellyjandrews profile image
Kelly Andrews

Here is a Codepen showing that your code should work.

codepen.io/kellyjandrews/pen/MQwBxx