Kevin
Kevin

Reputation: 1614

Dynamically hiding elements in a list without the hidden elements occupying empty space on the page

I need to hide elements based on what a user does. if he presses "a only", I can say something like

for(i=0;i<document.getElementsByClassName("b").length;i++){
      document.getElementsByClassName("b")[i].style.visibility="hidden";
 }

but this will leave empty spaces between elements in the list (the invisible elements still occupy space), which looks bad, is there a better way this can be done.

Upvotes: 1

Views: 635

Answers (4)

Shoib Mohammed A
Shoib Mohammed A

Reputation: 328

For visibility:hidden, the javascript parser will parse the elements css properties and hides, it actually exist on dom, but user cannot see. For display: none, when javascript parser finds the element with display, it just ignore the element and it move ahead. So you have to user display: none;

Upvotes: 0

Edd Morgan
Edd Morgan

Reputation: 2923

Yep. You are setting the visibility CSS property to hidden. This stops the element from being displayed, but it still occupies space.

You want to set the display property to be none. This removes it from being displayed, and stops it occupying space - effectively removing it from the document, at least as far as displaying it is concerned.

for(i=0;i<document.getElementsByClassName("b").length;i++){
    document.getElementsByClassName("b")[i].style.display = "none";
}

Upvotes: 2

Nathan Friend
Nathan Friend

Reputation: 12804

Use display: none instead of visiblity: hidden. The visibility property only hides the element; the display property actually removes the element from the layout.

Upvotes: 1

Mike Brant
Mike Brant

Reputation: 71384

try style.display="none"

Using visibilty="hidden", the elements will still take up their calculated space on the page.

You may also consider using jQUery. It makes tasks like these incredibly simple.

Upvotes: 4

Related Questions