If I wanted to hide all elements except for those within a <div id="content"> (including div#content itself), I could use the following CSS:
*
{
visibility: hidden !important;
}
div#content, div#content *
{
visibility: visible !important;
}
One thing to note about this solution is that the hidden elements still take up space. Unfortunately, not all elements have the same display attribute, so you cannot simple simply replace visibility above with display.
Using JavaScript, how can I set all elements to that are not within the <div id="#content"> ‘family’ to display: none?
A general purpose solution to change the style on the fewest objects, but make sure that
#contentand all it’s sub-elements are visible requires an algorithm to traverse up from#contentand hide all siblings at each level up without ever hiding an ancestor of#content. Because this starts at#contentand goes up, it never hides any elements inside of#content.Caveat: this first version does not hide text nodes that are siblings of an ancestor of #content (all other text nodes outside of #content are hidden because their parent is hidden). To hide those text nodes too, they would have to get wrapped in a
<span>tag so the style could be set on the<span>tag, but I don’t know if the OP needs that level of complexity or wants the text nodes wrapped in that way.For completeness, here’s a version that will wrap parent sibling text nodes so they can also be set to
display: none. This may or may not be needed depending upon the source HTML:And a working demo: http://jsfiddle.net/jfriend00/yVWDx/