Home > Web Front-end > JS Tutorial > How Can I Show and Hide DIV Elements Using JavaScript?

How Can I Show and Hide DIV Elements Using JavaScript?

Barbara Streisand
Release: 2024-12-09 16:09:11
Original
380 people have browsed it

How Can I Show and Hide DIV Elements Using JavaScript?

Show/Hide 'div' Using JavaScript

When building a website, toggling the visibility of elements is often desirable. This can be achieved using JavaScript. However, if you're encountering issues with your code, consider these potential solutions:

Manipulating the 'display' Property

To show or hide an element, set the style property 'display' to the desired value:

// Hide an element
element.style.display = 'none';

// Show an element
element.style.display = 'block';
Copy after login

Manipulating the 'visibility' Property

If you want an element to still occupy space while hidden, adjust the 'visibility' property instead:

// Hide an element
element.style.visibility = 'hidden';

// Show an element
element.style.visibility = 'visible';
Copy after login

Handling Collections of Elements

To hide multiple elements, iterate and set each element's 'display' to 'none':

function hide(elements) {
  for (var i = 0; i < elements.length; i++) {
    elements[i].style.display = 'none';
  }
}
Copy after login

Applying the Fix to Your Code

In your code, the second function isn't working because it's attempting to replace div2 with div1's content. To show div2, replace this line in the second function:

document.getElementById('replace_target').innerHTML = document.getElementById('source').innerHTML;
Copy after login

with this:

document.getElementById('replace_target').innerHTML = document.getElementById('target').innerHTML;
Copy after login

By adjusting these properties and applying these techniques, you should now be able to toggle the visibility of your divs as desired.

The above is the detailed content of How Can I Show and Hide DIV Elements Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template