Reputation: 8284
My goal is to detect if my element is displayed firstly; I guess narrowed down to display: block;
.
If it is; I'd like to iterate through all the elements underneath it within the document to add classes to them. The elements are dynamic; so I just need to add a common selector so that I can hide them (or display: none;
) them - when my first element's display: block;
is met.
Below is what I have; I'm mainly wondering how to detect if elements are underneath #banner
> if so add a common selector (class) to them so that I can then hide (display:none;
)
function CheckIfExistThenHideBelow () {
var inElgbl = document.getElementById('banner');
if (typeof(inElgbl) != 'undefined' && inElgbl != null)
{
// How to check if below element inElgbl in doc?
var divsToHide = document.getElementsByClassName("below");
for(var i = 0; i < divsToHide.length; i++){
divsToHide[i].style.display = "none";
}
}
Upvotes: 0
Views: 89
Reputation: 65825
This is simpler than you think. Just loop over the target element's siblings that come after it and hide each by applying a class.
function removeSiblingsAfter(someElement){
// Check some element to see if it is currently being displayed as a block
if(getComputedStyle(someElement).display === "block"){
// Begin looping while there is a next sibling that is an element
while(someElement.nextElementSibling){
// Adjust the looping variable to be the next sibling
// so that the loop can eventually end
someElement = someElement.nextElementSibling;
someElement.classList.add("hidden"); // Hide each sibling
}
}
}
removeSiblingsAfter(document.getElementById("sampleTarget"));
.hidden { display:none; }
<div>Sibling Before<div>
<div id="sampleTarget">Target Element</div>
<div>Sibling After</div>
<div>
<a href="http://example.com">Sibling After</a>
</div>
<div>Sibling After</div>
Upvotes: 1