J Fabian Meier
J Fabian Meier

Reputation: 35833

Hide elements of HTML page and uncover one by one

I like to first hide the top level elements of a HTML page and then uncover them one by one.

I managed to do this with paragraphs:

var uncoverCount = 0;

function uncoverSomething() {
    var arrOfPtags = document.getElementsByTagName("p");

    if (uncoverCount < arrOfPtags.length) {
        uncoverCount++;
    }

    for (var i = 0; i < uncoverCount; i++) {
        arrOfPtags[i].style.visibility = "visible";
    }
}

function hideEverything() {

    var arrOfPtags = document.getElementsByTagName("p");

    for (var i = 0; i < arrOfPtags.length; i++) {
        arrOfPtags[i].style.visibility = "hidden";
    }
}

But I would like to do this not only for "p" elements, but also for "h1", "ul" etc., meaning all top-level elements of the document.

So when uncoverSomething() is called, it should uncover the next element irrespective if it is a "p", "h1" or anything else.

How can I do that?

Upvotes: 0

Views: 104

Answers (1)

Balastrong
Balastrong

Reputation: 4464

Wanna try something like that? First I hide every top element inside .container by adding .hidden, then I search for the first .hidden and remove that class at each button press.

function revealNext() {
  var next = document.querySelector(".container > .hidden");
  if (next) next.classList.remove("hidden");
}

function hideAll() {
  var elements = document.querySelectorAll(".container > *");
  elements.forEach(e => e.classList.add("hidden"));
}
.hidden {
visibility: hidden;
}
<button onClick="hideAll()">Hide</button>
<button onClick="revealNext()">Reveal</button>
<div class="container">
<div>el1</div>
<p>el2</p>
<span>nested<span>stuff<span>here</span></span></span>
<h1>more stuff</h1>
</div>

Upvotes: 1

Related Questions