views:

106

answers:

2

Another short Q, is there any short piece of code to get all DIVs on a page which have the visibility set to 'block' or 'inline'?

Thanks

+1  A: 

It's easy with jQuery...

$("div:visible")

But if you want to be old school...

var divs = document.getElementsByTagName("DIV");
var elems = [];

for(var i = 0; i < divs.length; i++) {
  var div = divs[i];
  var vis = div.style.visibility;

  if(vis == 'block' || vis == 'inline')
    elems.push(div);
}
Josh Stodola
what if Im not using jquery?
Camran
@Camran Answer updated. I would recommend jQuery, it really speeds up development time and prevents headaches.
Josh Stodola
The non-jQuery version is flawed: I think you mean `display` rather than `visibility`, and it will only work when the display is explicitly set on the element's style. If you had a document containing some normal (visible) elements and no CSS, this function wouldn't return any elements. You need to use some combination of IE's `currentStyle` object and `getComputedStyle()` method to do this.
Tim Down
@Tim Wrong. I answered what he asked (precisely). Read the question, and then read my answer. Camran doesn't say anything about `display`, and he does not say anything about elements that do not explicitly set the property. Ok? I know what you are saying, but that's not what he asked. Thanks, and have a great day.
Josh Stodola
If anything, the jQuery version is flawed.
Josh Stodola
This isn't really worth arguing about, but I can't help myself. I take your point, but I think it's clear the OP either means `visbility` (in which case `inline` and `block` are invalid) or (more likely) means `display`. Also, it's not clear from the OP's phrasing whether he means what you've inferred (just elements with CSS `visibility` explicitly set to one of two invalid values) or what I've inferred (any element whose computed CSS `display` is `inline` or `block`). Yours is a precise, literal reading of it; mine is (I'd say) the more natural and likely.
Tim Down
A: 

Using jQuery:

$("div:visible")

http://api.jquery.com/visible-selector/

Bill Paetzke