Show/hide ‘div’ using JavaScript
In order to show or hide an element, manipulate the element’s style property. In most cases, you probably just want to change the element’s display property:
element.style.display = 'none'; // Hide element.style.display = 'block'; // Show element.style.display = 'inline'; // Show element.style.display = 'inline-block'; // Show
Alternatively, if you would still like the element to occupy space (like if you were to hide a table cell), you could change the element’s visibility property instead:
element.style.visibility = 'hidden'; // Hide element.style.visibility = 'visible'; // Show
Hiding a collection of elements:
If you want to hide a collection of elements, just iterate over each element and change the element’s display to none :
// Usage: hide(document.querySelectorAll('.target')); hide(document.querySelector('.target')); hide(document.getElementById('target'));
hide(document.querySelectorAll('.target')); function hide (elements) < elements = elements.length ? elements : [elements]; for (var index = 0; index < elements.length; index++) < elements[index].style.display = 'none'; >>
This div will be hidden. This span will be hidden as well.
Showing a collection of elements:
Most of the time, you will probably just be toggling between display: none and display: block , which means that the following may be sufficient when showing a collection of elements.
You can optionally specify the desired display as the second argument if you don’t want it to default to block .
function show (elements, specifiedDisplay) < elements = elements.length ? elements : [elements]; for (var index = 0; index < elements.length; index++) < elements[index].style.display = specifiedDisplay || 'block'; >>
// Usage: var elements = document.querySelectorAll('.target'); show(elements); show(elements, 'inline-block'); // The second param allows you to specify a display value
var elements = document.querySelectorAll('.target'); show(elements, 'inline-block'); // The second param allows you to specify a display value show(document.getElementById('hidden-input')); function show (elements, specifiedDisplay) < elements = elements.length ? elements : [elements]; for (var index = 0; index < elements.length; index++) < elements[index].style.display = specifiedDisplay || 'block'; >>
Inline span..
Alternatively, a better approach for showing the element(s) would be to merely remove the inline display styling in order to revert it back to its initial state. Then check the computed display style of the element in order to determine whether it is being hidden by a cascaded rule. If so, then show the element.
function show (elements, specifiedDisplay) < var computedDisplay, element, index; elements = elements.length ? elements : [elements]; for (index = 0; index < elements.length; index++) < element = elements[index]; // Remove the element's inline display styling element.style.display = ''; computedDisplay = window.getComputedStyle(element, null).getPropertyValue('display'); if (computedDisplay === 'none') < element.style.display = specifiedDisplay || 'block'; >> >
show(document.querySelectorAll('.target')); function show (elements, specifiedDisplay) < var computedDisplay, element, index; elements = elements.length ? elements : [elements]; for (index = 0; index < elements.length; index++) < element = elements[index]; // Remove the element's inline display styling element.style.display = ''; computedDisplay = window.getComputedStyle(element, null).getPropertyValue('display'); if (computedDisplay === 'none') < element.style.display = specifiedDisplay || 'block'; >> >
(If you want to take it a step further, you could even mimic what jQuery does and determine the element’s default browser styling by appending the element to a blank iframe (without a conflicting stylesheet) and then retrieve the computed styling. In doing so, you will know the true initial display property value of the element and you won’t have to hardcode a value in order to get the desired results.)
Toggling the display:
Similarly, if you would like to toggle the display of an element or collection of elements, you could simply iterate over each element and determine whether it is visible by checking the computed value of the display property. If it’s visible, set the display to none , otherwise remove the inline display styling, and if it’s still hidden, set the display to the specified value or the hardcoded default, block .
function toggle (elements, specifiedDisplay) < var element, index; elements = elements.length ? elements : [elements]; for (index = 0; index < elements.length; index++) < element = elements[index]; if (isElementHidden(element)) < element.style.display = ''; // If the element is still hidden after removing the inline display if (isElementHidden(element)) < element.style.display = specifiedDisplay || 'block'; >> else < element.style.display = 'none'; >> function isElementHidden (element) < return window.getComputedStyle(element, null).getPropertyValue('display') === 'none'; >>
// Usage: document.getElementById('toggle-button').addEventListener('click', function () < toggle(document.querySelectorAll('.target')); >);
document.getElementById('toggle-button').addEventListener('click', function () < toggle(document.querySelectorAll('.target')); >); function toggle (elements, specifiedDisplay) < var element, index; elements = elements.length ? elements : [elements]; for (index = 0; index < elements.length; index++) < element = elements[index]; if (isElementHidden(element)) < element.style.display = ''; // If the element is still hidden after removing the inline display if (isElementHidden(element)) < element.style.display = specifiedDisplay || 'block'; >> else < element.style.display = 'none'; >> function isElementHidden (element) < return window.getComputedStyle(element, null).getPropertyValue('display') === 'none'; >>
Toggle the span. Toggle the div.
Hiding and showing div blocks in html
I am a beginner to html and in the below code , i have tried to hide and show contents using div blocks. I am able to hide/ show the second div block but on clicking the first div block it doesn’t work! Dunno where it is going wrong. Any help would be appreciated.
function hideshow(which)
@mdesdev: this has absolutely nothing to do with why this code is not working and until the HTML is valid slideToggle() won’t be working either!
@aarish: Check your code in the browser console, under the element tab you can see that your HTML has been altered compared to how you have it declared originally. the reason for this is that div tags cannot follow tr tags and the browser is trying to do it’s best guess work to correct it. Hence it moves the invalid div s outside the tables. This might not be the same result between all browsers. Invalid HTML can be unpredictable at best. validator.w3.org/check is a great tool to validate your HTML.
6 Answers 6
Did you mean to have another table row in there?
The same issue applies to the second div element
+1 Note for OP: The reason your second div works, although it is incorrectly placed following a tr tag as well is because the browser moves the complete div outside and below the first table.
The problem isn’t your javascript but your HTML, it’s not valid. Your javascript, although a bit odd (why do you check if getElementById exist? You used it to call the function!), is OK.
The problem is that your DIVs are floating in the middle of two TR. A table structure is:
// a row // one cell // end of a row
end of table
What happens when you put stuff between Rows is undefined behavior. If you check your DOM in Chrome for instance, you’ll see that your DIVs are actually empty and that the text (which you put in another table, my eyes. ) has ‘escaped’ out of them. And that’s why it does nothing when you click: the style is updated, but there is nothing in it.
Funny thing: if you fix just the first DIV, the second DIV will start not working. It all depends on how the browser parse your invalid HTML and it’s a bit random. Always close your tags, and always make sure you are following the basic structures. Like putting a TR within a UL instead of a LI (I have seen it.)
How to show hidden elements in Javascript HTML
I have hidden my div’s with hidden=»true» which is working but I want to show it after a button click. I work with Node.js and this part must be coded in Javascript. html:
socket.on('loginInServer',function(data)< $('.sideDiv').show(); >);
5 Answers 5
As said above, you should get rid of the hidden attribute and hide the element using the css instead.
Then the jquery’s show() method will work.
But you probably want to hide it in the first place not using the hidden attribute, which honestly I have not seen anyone use (other than for hidden form fields).
The simplest way is to have this in your css:
Or if you’re lazy you can embed this on the element itself in html:
Then when your page loads, it will be hidden and what you’re doing with .show() will work since that jQuery function operates on the «display» style of a dom element.
Remove the attribute using removeAttr() method.
ocket.on('loginInServer',function(data)< $('.sideDiv').removeAttr('hidden'); >);
Or update the attribute to false using attr() method.
ocket.on('loginInServer',function(data)< $('.sideDiv').attr('hidden', false); >);
Or set the property false using prop() method.
ocket.on('loginInServer',function(data)< $('.sideDiv').prop('hidden', false); >);
FYI : For hiding element set CSS display:none; which would be the much better way and later you can show using show() method.
The style «display:none» and attribute hidden=»true» renders differently.
The hidden global attribute is a Boolean attribute indicating that the element is not yet, or is no longer, relevant. For example, it can be used to hide elements of the page that can’t be used until the login process has been completed. Browsers won’t render elements with the hidden attribute set.
jQuery’s show changes the style of an element and does not modify the attribute hidden
. This is roughly equivalent to calling .css( «display», «block» ) .
You will want to use jQuery’s attr or prop to modify the attribute hidden
$('.sideDiv').attr('hidden', false); $('.sideDiv').prop('hidden', false);
How to make a DIV visible and invisible with JavaScript?
@JackStone: No, that’s only if you’re already using the jQuery library. Some people just like to promote it on every JavaScript question. Even if you were, .hide() doesn’t set visibility. It sets display.
@am not i am you have clearly failed to understand that jQuery is really great and does all things. (Image source)
For something like this a good answer should contain both a plain JS solution and one showing the advantage of using a library — in this case, not having to deal with inline vs block when using display to show an element.
9 Answers 9
if [DIV] is an element then
[DIV].style.visibility='visible'
visibility has the side effect that the space occupied by the element remains reserved. That may or may not be what the OP wants
@JackStone: It depends on what you mean by the «name» of your div. If it’s a variable that is referencing the div, then yes.
So if my div were name testdiv , it would be document.getElementById(‘testdiv’).style.visibility = ‘hidden’; ?
Let’s assume you do not use a library such as jQuery.
If you do not already have a reference to the DOM element, get one using var elem = document.getElementById(‘id’);
Then you can set any CSS property of that element. To show/hide, you can use two properties: display and visibility , which have slightly different effects:
Adjusting style.display will look as if element is not present at all («removed»).
elem.style.display = 'none'; // hide elem.style.display = 'block'; // show - use this for block elements (div, p) elem.style.display = 'inline'; // show - use this for inline elements (span, a)
or style.visibility will actually make the div still be there, but be «all empty» or «all white»
elem.style.visibility = 'hidden'; // hide, but lets the element keep its size elem.style.visibility = 'visible';
If you are using jQuery, you can do it even easier as long as you want to set the display property:
It will automatically use the appropriate display value; you do not have to care about the element type (inline or block). Additionally, elem can not only be a DOM element but also a selector such as #id or .class or anything else that is valid CSS3 (and more!).