Home >Web Front-end >JS Tutorial >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';
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';
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'; } }
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;
with this:
document.getElementById('replace_target').innerHTML = document.getElementById('target').innerHTML;
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!