Put all the .manifest
elements in a collection and loop over them, hiding each as you iterate (use CSS classes rather than inline CSS to do this as a best practice). Then, just show the .element
item and create the new manifest
element when the loop is complete.
And, don't use .getElementsByClassName()
, which can really hurt performance in general, but in this case is the source of your issue. .getElementsByClassName()
returns a "live node list", which keeps track of all matching elements at the time you create it and as the DOM gets changed from that point forward. Because you are adding a new element later, but one that has the same class (manifest
) as the live node list contains, it's part of that node list and if you loop over that list and hide all the elements, the new element will be part of it. As you can see from the code below, no matter how many times you click the button (and loop over the manifest
class items), the newly created one won't go away because we're not using a live node list here - - querySelectorAll()
returns a "static node list".
document.querySelector("button").addEventListener("click", function(event){
// Get all the .manifest items and loop over them
document.querySelectorAll(".manifest").forEach(function(item){
item.classList.add("hidden"); // Hide the item
});
document.querySelector(".element").classList.remove("hidden"); // Show this item
// Now append a new manifest element that will be shown
let manifest = document.createElement("div");
manifest.textContent = "Dynamically added manifest element";
document.querySelector("div").appendChild(manifest);
});
.hidden { display:none; }
<div>
<div class="manifest">Manifest Element</div>
<div class="manifest">Manifest Element</div>
<div class="manifest">Manifest Element</div>
<div class="manifest">Manifest Element</div>
<div class="manifest">Manifest Element</div>
<div class="element hidden">Elment Element</div>
</div>
<button>Go!</button>