Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide/show div tags using JavaScript?

Basically, I'm trying to make a link that, when pressed, will hide the current body div tag and show another one in its place, unfortunately, when I click the link, the first body div tag still appears. Here is the HTML code:

<div id="body">
    <h1>Numbers</h1>
</div>
<div id="body1">
    Body 1
</div>

Here is the CSS code:

#body {
    height: 500px;
    width: 100%;
    margin: auto auto;
    border: solid medium thick;
}

#body1 {
    height: 500px;
    width: 100%;
    margin: auto auto;
    border: solid medium thick;
    display: hidden;
}

Here is the JavaScript code:

function changeDiv() {
  document.getElementById('body').style.display = "hidden"; // hide body div tag
  document.getElementById('body1').style.display = "block"; // show body1 div tag
  document.getElementById('body1').innerHTML = "If you can see this, JavaScript function worked"; // display text if JavaScript worked
}

NB: CSS tags are declared in different files

like image 549
Shaughn Williams Avatar asked Mar 06 '13 23:03

Shaughn Williams


People also ask

How do I hide a div tag?

The document. getElementById will select the div with given id. The style. display = "none" will make it disappear when clicked on div.

How do I hide a tag in JavaScript?

visibility is when using visibility: hidden, the tag is not visible, but space is allocated. Using display: none, the tag is also not visible, but there is no space allocated on the page. In HTML, we can use the hidden attribute to hide the specified element.

How do I hide a div inspect?

We can hide an element by inspecting it with Chrome DevTools, right-clicking the element under the Elements tab, and choosing the Hide element menu from the context menu. If you're a fan of using the shortcut, then pressing the h key has the same effect.

Can JavaScript hide HTML elements?

Using Css style we can hide or show HTML elements in javascript. Css provides properties such as block and none to hide/show the HTML elements.


1 Answers

Have you tried

document.getElementById('body').style.display = "none";

instead of

document.getElementById('body').style.display = "hidden";?

like image 102
Iwo Kucharski Avatar answered Nov 14 '22 21:11

Iwo Kucharski