how to hide every <div> ?

B

benzwt

I use the following function to hide a <div> named one.

function hideObject() {
if (ns4) {
document.n1.visibility = "hide";
}
else if (ie4) {
document.all['n1'].style.visibility = "hidden";
}
else if (nn6) {
document.getElementById('one').style.visibility = "hidden";
}
}

the code will becomes clumsy if I have many <div> to hide.
Is there good way to hide every <div> ?
 
L

lallous

Hello

One way is to put the IDs of all divs in an array then loop through the
array and hide each element.

Or, I don't know how but know it is possible, loop in the whole page
searching for "div" tags then hide that element.
 
E

Evertjan.

the code will becomes clumsy if I have many <div> to hide.
Is there good way to hide every <div> ?

IE, not tested:

var coll = document.all.tags("DIV");
if (coll!=null) {
for (i=0; i<coll.length; i++) {
coll.style.visibility = "hidden";
}
}

or more static:

<style>
div {visibility:hidden;}
</style>
 
J

john henry bonham

I use the following function to hide a <div> named one.

function hideObject() {
if (ns4) {
document.n1.visibility = "hide";
}
else if (ie4) {
document.all['n1'].style.visibility = "hidden";
}
else if (nn6) {
document.getElementById('one').style.visibility = "hidden";
}
}

the code will becomes clumsy if I have many <div> to hide.
Is there good way to hide every <div> ?

for ( var i = 0 ; i < document.getElementsByTagName{ 'div' ).length ; i++ );
{
document.getElementsByTagName{ 'div' )[ i ].style.visibility =
'hidden';
}

will work in IE5+, NS6+, Mozilla & Opera and other browsers less than 3
years old :eek:

Rob
http://www.avagio.co.uk
 
M

Mark Preston

I use the following function to hide a <div> named one.

function hideObject() {
if (ns4) {
document.n1.visibility = "hide";
}
else if (ie4) {
document.all['n1'].style.visibility = "hidden";
}
else if (nn6) {
document.getElementById('one').style.visibility = "hidden";
}
}

the code will becomes clumsy if I have many <div> to hide.
Is there good way to hide every <div> ?

I've not tried it so can't give you the code, but someone may be able to
fill in the blanks (and its quite an interesting question). There should
be a way to set up a standard style like:-

<style> div {display:block} </style>

Then, in your script, to refer to the document.style.display and set it
from "block" to "none". That should hide them all.
 
G

Grant Wagner

I use the following function to hide a <div> named one.

function hideObject() {
if (ns4) {
document.n1.visibility = "hide";
}
else if (ie4) {
document.all['n1'].style.visibility = "hidden";
}
else if (nn6) {
document.getElementById('one').style.visibility = "hidden";
}
}

the code will becomes clumsy if I have many <div> to hide.
Is there good way to hide every <div> ?

Browser detection isn't a very good idea (ns4, ie4, etc variables),
use feature detection. And it's probably a good idea to attempt to
use the most modern mechanism first. Below is a generic function that
will set the visibility of any <div>/<layer> in most browsers to
hidden:

<script type="text/javascript">
function hideObject(id) {
var o;
if (document.getElementById) {
o = document.getElementById(id).style;
} else if (document.layers) {
o = document.layers;
} else if (document.all) {
o = document.all[id].style;
}
if (o) {
o.visibility = 'hidden';
}
}

// then

hideObject('yourId1');
hideObject('yourId2');
hideObject('yourId3');

// or

for (var i = 0; i < arrayOfDivIds.length; i++) {
hideObject(arrayOfDivIds);
}
</script>

Note that you can *set* "hidden" in Netscape 4, but if queried, NS4
returns "hide" or "show". This script still isn't optimum because it
tests which DOM is supported for each call. The performance
difference probably won't matter in most cases.
 
T

Thomas 'PointedEars' Lahn

Grant said:
Browser detection isn't a very good idea (ns4, ie4, etc variables),
use feature detection. And it's probably a good idea to attempt to
use the most modern mechanism first. Below is a generic function that
will set the visibility of any <div>/<layer> in most browsers to
hidden:

<script type="text/javascript">
function hideObject(id) {
var o;
if (document.getElementById) {
o = document.getElementById(id).style;
} else if (document.layers) {
o = document.layers;

document.layers is IIRC an Array object. The object itself
has no visibility property, so I do not understand why you
are including it here. It would be more reasonable to try to
access the id-th layer or not supporting the NN4 DOM at all.
} else if (document.all) {
o = document.all[id].style;

While the IE DOM has an ambiguity that methods of host objects
can be used as collections (and vice-versa), the documentation
at MSDN uses the method syntax and this is why I think one
should stick to that.
}
if (o) {
o.visibility = 'hidden';
}
}

This was my first approach for dhtml.js, too. Yet testing the DOM every
time the method is called is not very efficient. Try this instead:

if (document.getElementById)
{
function getElemById(id)
{
return document.getElementById(id);
}
}
else if (document.all)
{
function getElemById(id)
{
return document.all(id);
}
}
else if (document.layers)
{
function getElemById(id)
{
return document.layers[id];
}
}

function hideObject(id)
{
var o = getElemById(id);
if (o)
{
(typeof o.style != "undefined")
? o.style.visibility = "hidden";
: o.visibility = "hidden";
}
}

Signatures are by convention (RFC) to be delimited by DashDashSpace
(`-- '), so compliant NetNews software (like mine) can handle them
differently (removing them automatically on reply, coloring them to
distinguish them from the rest of the article, hide them if display
is undesired etc.)
<http://insideoe.tomsterdam.com/problems/bugs.htm#sigseparator>
explains how to achieve that with Outlook Express which will otherwise
truncate trailing spaces on submit no matter how many you type when
composing the mail/article.


PointedEars
 
G

Grant Wagner

Thomas said:
document.layers is IIRC an Array object. The object itself
has no visibility property, so I do not understand why you
are including it here. It would be more reasonable to try to
access the id-th layer or not supporting the NN4 DOM at all.

Given that line in the context of the rest of the code, I think it's fairly
obvious my intent was "document.layers[id]" rather then "document.layers". A
more appropriate response might have been: "you probably meant
'document.layers[id]'". A correction of my mistake to the original poster
was necessary, a 4-line explanation on what I did wrong given the context of
the rest of the code was not.

Of course, if your intent was to be intentionally obtuse ("... I do not
understand why you are including it here.") then I guess you succeeded.
} else if (document.all) {
o = document.all[id].style;

While the IE DOM has an ambiguity that methods of host objects
can be used as collections (and vice-versa), the documentation
at MSDN uses the method syntax and this is why I think one
should stick to that.

It's a collection, it gets accessed using the collection syntax. MSDN
documentation indicates that document.forms(), .links(), .elements(), etc
should also use the method syntax, but I certainly don't use:

<!--[if IE]>
<script type="text/javascript">
var el = document.forms('theForm').elements('theElement');
</script>
<![endif]-->
<![if !IE]>
<script type="text/javascript">
var el = document.forms['theForm'].elements['theElement'];
</script>
<![endif]>

everywhere I access a form element[] or link[].
This was my first approach for dhtml.js, too. Yet testing the DOM every
time the method is called is not very efficient. Try this instead:

Which is why I wrote: "This script still isn't optimum because it tests
which DOM is supported for each call. The performance difference probably
won't matter in most cases."

I did not want to confuse the issue by combining more advanced concepts with
the concept of feature detection.
else if (document.layers)
{
function getElemById(id)
{
return document.layers[id];
}
}

In my environment Netscape 4 is more likely to be in use than Internet
Explorer 4, so I move the document.layers test up simply to document it's
relative importance. Also, I'd probably add the following catch-all else:

else {
function getElemById(id) { return null; }
}
function hideObject(id)
{
var o = getElemById(id);
if (o)
{
(typeof o.style != "undefined")
? o.style.visibility = "hidden";
: o.visibility = "hidden";
}
}

Depending on requirements, I might code it as:

function setVisibility(id, visible) {
var o = getElemById(o);
if (o) {
if (typeof o.style != 'undefined') {
o.style.visibility = (visible ? 'visible' : 'hidden');
return (o.style.visibility == (visible ? 'visible' : 'hidden'));

} else {
o.visibility = (visible ? 'show' : 'hide');
return (o.visibility == (visible ? 'show' : 'hide'));
}
}
return false;
}

I completely acknowledge the above code is not perfect. It is certainly
possible to get false positives, where the visibility (or other) property is
confirmed as being set on the object but nothing happened in the browser
(Opera 6 and innerHTML are a good example of this). It is possible (but I
feel less likely) to get false negatives. If the visibility property is not
the value you set it to, then either the DOM performed the requested action
and somehow "reset" the value, or the value simply did not get set. Despite
the obvious unreliability of returning a boolean from such a function, I
still think there are circumstances where knowing that setVisibility()
couldn't locate or change the visibility on the specified element can be of
value.
Signatures are by convention (RFC) to be delimited by DashDashSpace
(`-- '), so compliant NetNews software (like mine) can handle them
differently (removing them automatically on reply, coloring them to
distinguish them from the rest of the article, hide them if display
is undesired etc.)
<http://insideoe.tomsterdam.com/problems/bugs.htm#sigseparator>
explains how to achieve that with Outlook Express which will otherwise
truncate trailing spaces on submit no matter how many you type when
composing the mail/article.

PointedEars

Thank you for the link, but I don't use Outlook Express so that article does
not help. I guess you'll just have to mentally filter out the three lines of
my sig.
 
R

Richard Cornford

Thomas 'PointedEars' Lahn wrote:
if (document.getElementById)
{
function getElemById(id)
{
return document.getElementById(id);
}
}
else ...
<snip>

By ECMA specification (section 13) a FunctionDeclaration is a
SourceElement, and SourceElements may be FunctionDeclarations or
Statements (section 14). Making it syntactically incorrect for a
FunctionDeclaration to appear within a Statement (including a block
statement). As a result of this the above must be a FunctionExpression
with optional identifier (no other valid interpretation is available
given the surrounding block statement).

However, also by ECMA specification (section 13), the identifier of a
FunctionExpression with optional identifier results in a new object
being added to the scope chain of the execution context in which the
expression is evaluated, the identifier is used to create a named
property of that object, a reference to the created function object
assigned to that named property and then the object being removed from
the scope chain. As a result the only code able to utilise the
identifier optionally provided with a FunctionExpression to refer to the
corresponding function object is code lexically contained within that
expression.

There is a longstanding bug in the JS implementation used in
Mozilla/gecko where an identifier optionally used with a
FunctionExpression leaks into the containing scope, but because that is
contrary to the ECMAScript specification it would not be a good idea to
author code to exploit that fault. The results could not be expected to
be cross-browser.

Richard.
 
R

Richard Cornford

john henry bonham wrote:
for (var i = 0 ;i < document.getElementsByTagName{ 'div' ).length ;
i++ ); {
document.getElementsByTagName{ 'div' )[ i ].style.visibility =
'hidden';
}
<snip>

Apart form the absence of verification for the browser's support for the
required features (which can be assumed to be in code previously
executed but not shown), This is a ridiculously inefficient formulation.
You are creating a *new* nodeList each time you read the - length -
property, and another *new* nodeList each time you assign a value to a -
visibility - property. So that is two nodeLists created for each
iteration of the loop (plus one when the length is exceeded).

A nodeList is specified as a "live" collection so we are not even
talking of just the overhead of creating a passive Array each time, but
the creation of quite a capable, complex and active object (then there
is the extra work for the garbage collector in destroying all of these
nodeLists).

It is considerably more efficient to assign a retrieved nodeList to a
local variable once and then iterate through its members by referring to
it through the local variable reference.

Richard.
 
T

Thomas 'PointedEars' Lahn

Richard said:
Thomas 'PointedEars' Lahn wrote:

<snip>

By ECMA specification (section 13) a FunctionDeclaration is a
SourceElement, and SourceElements may be FunctionDeclarations or
Statements (section 14). Making it syntactically incorrect for a
FunctionDeclaration to appear within a Statement (including a block
statement). As a result of this the above must be a FunctionExpression
with optional identifier (no other valid interpretation is available
given the surrounding block statement).

OK, then one should use a FunctionExpression:

if (document.getElementById)
{
this.getElemById = function getElemById(id)
{
return document.getElementById(id);
}
}

The point is that defining a function/method once removes the
necessity for checking for DOM features every time it is called.


PointedEars
 
T

Thomas 'PointedEars' Lahn

Grant said:
Thomas said:
document.layers is IIRC an Array object. The object itself
has no visibility property, so I do not understand why you
are including it here. It would be more reasonable to try to
access the id-th layer or not supporting the NN4 DOM at all.

Given that line in the context of the rest of the code, I think it's
fairly obvious my intent was "document.layers[id]" rather then
"document.layers".

It certainly was not, especially not to a newbie. And now?
A more appropriate response might have been: "you probably meant
'document.layers[id]'". A correction of my mistake to the original
poster was necessary, a 4-line explanation on what I did wrong
given the context of the rest of the code was not.

Go whine about it.
} else if (document.all) {
o = document.all[id].style;

While the IE DOM has an ambiguity that methods of host objects
can be used as collections (and vice-versa), the documentation
at MSDN uses the method syntax and this is why I think one
should stick to that.

It's a collection,
Proof?

it gets accessed using the collection syntax. MSDN
documentation indicates that document.forms(), .links(), .elements(), etc
should also use the method syntax, but I certainly don't use:

<!--[if IE]>
<script type="text/javascript">
var el = document.forms('theForm').elements('theElement');
</script>
<![endif]-->
<![if !IE]>
<script type="text/javascript">
var el = document.forms['theForm'].elements['theElement'];
</script>
<![endif]>
[...]

You confuse DOM Level 0/2+ and the IE DOM. `document.forms'
and `elements' are both collections, specified in DOM Level
0/2+ and *also* became part of the IE DOM. document.all is
part of the IE DOM *only*.
Which is why I wrote: "This script still isn't optimum because it tests
which DOM is supported for each call. The performance difference probably
won't matter in most cases."

I did not want to confuse the issue by combining more advanced concepts
with the concept of feature detection.

Keeping things as simple as possible is not always the best approach.
else if (document.layers)
{
function getElemById(id)
{
return document.layers[id];
}
}

In my environment Netscape 4 is more likely to be in use than Internet
Explorer 4, so I move the document.layers test up simply to document it's
relative importance.

I assure you that no Web user cares about the environment of the developer.
Netscape 4.x are about to become extinct at least as Web browser, even its
vendor does not support them anymore for more than two years now. It
should have the least possible priority in an authorative feature test.
Also, I'd probably add the following catch-all else:

else {
function getElemById(id) { return null; }
}

True, I forgot that in my example but it is already included in nightly
versions of dhtml.js.
function hideObject(id)
{
var o = getElemById(id);
if (o)
{
(typeof o.style != "undefined")
? o.style.visibility = "hidden";
: o.visibility = "hidden";
}
}

Depending on requirements, I might code it as:

function setVisibility(id, visible) {
[...]

Yes, indeed. (dhtml.js contains a visibility() method to do exactly that.)

Signatures are by convention (RFC) to be delimited by DashDashSpace
(`-- '), so compliant NetNews software (like mine) can handle them
differently (removing them automatically on reply, coloring them to
distinguish them from the rest of the article, hide them if display
is undesired etc.) [...]

Thank you for the link, but I don't use Outlook Express so that article
does not help.

I'm sorry. Somehow I confused you with another poster, not checking the
headers prior. (But hopefully subscribers with OE will read my article.)
I guess you'll just have to mentally filter out the three lines of my sig.

Well, with Netscape 4.x it helps not to use the HTML composer. Since HTML
messages are unwanted on Usenet anyway and for many people in e-mails, too,
disabling it would be a Good Thing anyway.
<http://www.holgermetzger.de/tips/signatur.html>
This is a screenshot from the German version, but HTH.


PointedEars
 
R

Richard Cornford

Thomas 'PointedEars' Lahn wrote:
The point is that defining a function/method once removes
the necessity for checking for DOM features every time it
is called.

Any point in the post of yours that I was replying to is irrelevant to
the observation that its implementation should be expected to fail in an
ECMA 262 (3rd edition) conforming script engine.

Richard.
 
J

john henry bonham

Richard said:
john henry bonham wrote:
for (var i = 0 ;i < document.getElementsByTagName{ 'div' ).length ;
i++ ); {
document.getElementsByTagName{ 'div' )[ i ].style.visibility =
'hidden';
}

<snip>

Apart form the absence of verification for the browser's support for the
required features (which can be assumed to be in code previously
executed but not shown), This is a ridiculously inefficient formulation.

Sorry you lost me. Can you explain that in layman's terms?

Also, you have spent alot of effort in this thread pointing out errors
and standars which is all well and good. What's your solution to the
problem? Or pray, tell us which solution offered is the best.

Thx,

Rob
 
T

Thomas 'PointedEars' Lahn

Richard said:
Thomas 'PointedEars' Lahn wrote:


Any point in the post of yours that I was replying to is irrelevant to
the observation that its implementation should be expected to fail in an
ECMA 262 (3rd edition) conforming script engine.

You may want to re-read the thread to notify the correction I made because
of your comments.


PointedEars
 
M

Michael Winter

Richard said:
john henry bonham wrote:
for (var i = 0 ;i < document.getElementsByTagName{ 'div' ).length;
i++ ); {
document.getElementsByTagName{ 'div' )[ i ].style.visibility =
'hidden';
}
<snip>
Apart form the absence of verification for the browser's supportfor the
required features (which can be assumed to be in codepreviously
executed but not shown), This is a ridiculouslyinefficient formulation.

Sorry you lost me. Can you explain that in layman's terms?

Just what he said.

Every time you call document.getElementsByTagName(), a supporting browser
must search the document for all such tags and build an array containing
them. To make matters worse, it must do this twice for each iteration:
once to get the length property, and again to get a reference to the i'th
object.

Note that I said "supporting browser", above. As you point out yourself,
this method is only supported by relatively recent browsers. There are
many people that use browsers that will not support this method, so this
script will do nothing more than cause an error.

To sort out the latter problem, use feature testing:

if(document.getElementsByTagName) {
// method supported

This should also be applied when accessing the style property.

For the former, call the method once, save the results, and use them in
the loop:

function setVisibility(e, v) {
if(e) {
if(e.style) {
e.style.visibility = v;
} else {
e.visibility = v;
}
}
}

function hideDivs() {
if(document.getElementsByTagName) {
var c = document.getElementsByTagName('DIV');

for(var i = 0, n = c.length; i < n; ++i) {
var e = c;

setVisibility(e, 'hidden');
}
}
}
Also, you have spent alot of effort in this thread pointing outerrors
and standars which is all well and good. What's yoursolution to the
problem? Or pray, tell us which solution offered isthe best.

Well, the above could be modified to use alternatives to
getElementsByTagName():

if(document.getElementsByTagName) {
var getRefsByName = function(n) {
return document.getElementsByTagName(n);
};
} else if(document.all && document.all.tags) {
var getRefsByName = function(n) {
return document.all.tags(n) || [];
};
/*
* Add any other alternatives here.
*
*/
} else {
var getRefsByName = function() {
return [];
};
}

function setVisibility(e, v) {
if(e) {
if(e.style) {
e.style.visibility = v;
} else {
e.visibility = v;
}
}
}

function hideDivs() {
var c = getRefsByName('DIV');

if(c) {
for(var i = 0, n = c.length; i < n; ++i) {
var e = c;

setVisibility(e, 'hidden');
}
}
}

Mike
 
R

Richard Cornford

john said:
Richard said:
john said:
for (var i = 0 ;i < document.getElementsByTagName{ 'div' ).length ;
i++ ); {
document.getElementsByTagName{ 'div' )[ i ].style.visibility =
'hidden';
}
<snip>
Apart form the absence of verification for the browser's support for
the required features (which can be assumed to be in code previously
executed but not shown), This is a ridiculously inefficient
formulation.

Sorry you lost me. Can you explain that in layman's terms?

Explain what exactly? I have explained the inefficiency, and the
requirement for feature detection is explained in the FAQ. But in
layman's terms I probably couldn't explain either as the majority of
laymen have no concepts or terminology that would applicable to computer
programming and tend to find the subject extremely tedious.
Also, you have spent alot of effort in this thread pointing out errors
and standars which is all well and good. What's your solution to the
problem? Or pray, tell us which solution offered is the best.

The question, as asked, is too superficial to make an assessment of what
an optimum response should be, at least in terms of the code that should
be applied to the problem.

Your proposal (and a number of others) has concentrated on taking the
words "hide every <div>" literally, regardless of the fact that hiding
every DIV in a document is extremely unlikely to be the real
requirement, or a good idea.

Grant Wagner's response, in providing a direct illustration of feature
detection applied in the context of the question, is probably going to
prove most valuable to the OP.

Thomas Lahn's interjection that Grant's implementation is less than
optimally efficient as it repeats tests that will have the same outcome
each time they are executed as they had on the first execution, is true,
but the applicability of that notion to the OP's context remains
unknown. Given the little that we know of the OP, I think that presentin
g a number of interdependent, feature detecting functions (even if
optimally efficient) as a direct substitution for the OP's single
original might have represented moving too far up the learning curve for
the OP to go in a single step. Even if it does represent a point the OP
must pass through at some time in order to consider themselves a
competent Javascript author.

Richard.
 
R

Richard Cornford

Thomas said:
You may want to re-read the thread to notify the correction I made
because of your comments.

I have no idea what you are going on about. While erroneous
implementation might tend to undermine the credibility of an individual
trying to make a point, any points made have validity, or not,
independent of example code intended as illustration.

Richard.
 
T

Thomas 'PointedEars' Lahn

Richard said:
Thomas said:
You may want to re-read the thread to notify the correction I made
because of your comments.

I have no idea what you are going on about. [...]

Is it as hot weather with you as with me? The correction I made
because of your comments which you snipped above is compliant to
ECMAScript 3, using FunctionExpressions!


PointedEars
 
R

Richard Cornford

Thomas said:
Richard said:
Thomas 'PointedEars' Lahn wrote:
You may want to re-read the thread to notify the
correction I made because of your comments.

I have no idea what you are going on about. [...]

Is it as hot weather with you as with me?

Why, would it have made more sense in cooler weather?
The correction I made because of your comments
which you snipped above is compliant to
ECMAScript 3, using FunctionExpressions!

Did anyone say that it wasn't? Indeed it is almost exactly the same as
one of the formulations used in the examples of feature detection that
appears in the FAQ notes.

Richard.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,812
Latest member
GracielaWa

Latest Threads

Top