Alert visible elements inside div (native javascript)
I was wondering if there is any way to alert or get to only the visible elements within a div, span or any parent element.
When using innerHTML, it obviously shows everything, including hidden elements that are only to be found in the source code. I need only the visible elements.
If it would help anything, all the invisible elements are hidden via display:none CSS (either set beforehand or dynamically via Javascript).
you can loop through all of the elements checking for the
Code:
getPropertyValue("visibility")
of their getComputed Style (and whatever the IE equivalent is) - this will exclude not only those that are hidden, but also those that are nested within elements that are hidden
If you don't use the obsolete alert( ) to do this and instead use a popon <div>, you can just copy the innerHTML and in the popon the visibilities will *likely* be the same so you don't have to change anything. ("likely" because it's possible the style depends on the container something is in.)
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
I am pretty sure I stated it is via "display: none;" (also when it's about any dynamic changes).
It is actually a combination of dynamic changes and <style> block.
And I do consider alert() to be obsolete, but I use it all the time to test Javascript functions to see if they works and output anything correctly.
It seems a bit weird to me that you would have to loop all of the different child elements. I just would like to get to what is in the element, just what is to be seen.
you could try it without a loop but to me it seems unlikely that you will save any time or code doing it that way. Maybe with a query selector, but even then you would have to loop through the selected elements to alert() them.
Much depends, I guess, on the structure of your html
If you use getComputedStyle(), you could do something like this:
Code:
var container = document.getElementById("yourContainerDiv");
var result = "";
var elems = container.getElementsByTagName("*"); // all elements, nested or not
for ( var e = 0; e < elems.length; ++e )
{
var elem = elems[e];
var elemStyle = getComputedStyle( elem ); // but need to provide IE alternative
if ( elemStyle.display != "none" && elemStyle.visibility != "hidden" )
{
result += "\n" + elem.innerText;
}
}
Or something along those lines. Not sure if you wanted to see all the tag names in the alert() or not.
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.