Short Version: Is it standard behaviour that myDiv.style.display (Javascript) returns blank when I have set that div to display:none in a master stylesheet, yet returns "none" when it is set via an inline style?
Long Version:
I have some divs that I hide and unhide via their display style, toggling it with Javascript between block and none. They always start off hidden (display:none) which I have been setting with inline styles thusly:
<div id="anID" class="aClass" style="display:none">
stuff
</div>
Here is the Javascript to toggle between none and block. The two chOpsXXX() functions just set the divSection.style.display to the opposite value (along with other housekeeping):
var divSection = document.getElementById("chOpsSection" + strSectionID);
var strDisplay = divSection.style.display;
if (strDisplay == "none") {
chOpsDisplaySection(strSectionID);
} else {
chOpsHideSection(strSectionID);
}
This all works fine when I use an inline style attribute to set the initial display:none style.
I am also setting other styles for these divs in master stylesheet. So I decided it might make sense to move the initial state of display:none to said stylesheet. I did so. I won't post it, I think you can picture it.
But when I did so, the div is initially hidden (display:none), but the first call to divSection.style.display returns an empty string (alert(strDisplay); returns a blank string, not null).
My Javascript shown above then hides it (becaues it doesn't equal "none") and then the next call to divSection.style.display returns "none" and everything works fine from there. (Same behaviour if I set it to inline in the master stylesheet: the div is initialy visible, and the first call to divSection.style.display returns a blank string).
This is easy enough to fix by checking for both "none" and "" in my Javascript above. But I would like to know if this returning of a blank string from divSection.style.display is standard behaviour.
All replies are welcome.
If you access to a DOM Element via JS(using for example getElementById) you'll not be able to read the computed style of that element, because it is defined inside the CSS file. To avoid this, you have to use property getComputedStyle(or currentStyle for IE).
function getStyle(id, name)
{
var element = document.getElementById(id);
return element.currentStyle ? element.currentStyle[name] : window.getComputedStyle ? window.getComputedStyle(element, null).getPropertyValue(name) : null;
}
Usage(JSFiddle):
var display = getStyle('myDiv', 'display');
alert(display); //will print 'none' or 'block' or 'inline' etc
It's not working because you removed it as a style attribute on your element, and placed it in an external stylesheet. DOM will not show attribute values that do not exist in the document object (DOM is merely an XML parser that reads your HTML document verbatim).
To find CSS values set in an external stylesheet, you have to parse document.styleSheets and find the matching selector(s).
This is where using a library like jQuery becomes really handy, because it parses external stylesheets, and has helper methods to get the full CSS applied to an element.
Example of how you would do this in jQuery:
value = $("#anID").css("display");
PS - Looking for an empty string won't work for you, either, because display: "" is not the same as display: "none" (and in fact, is the same as display: block, for a div, because a blank essentially means inherit)
My solution:
Create class .hidden
.hidden {
display: none !important;
}
Javascript:
function toggleHidden(id) {
var x = document.getElementById(id);
x.classList.toggle('hidden');
}
The javascript display property stands for only for DOM attribute
Mozilla JS wiki, Returns an object that represents the element's style attribute.
W3schools, The Style object represents an individual style statement
You could use jquery's css method to get a mixed display value like
alert($("#foo").css("display"))
It should show none even if you set it with css
Related
For some reason I can't access HTML element's display style's value.
Here's my JavaScript code:
var el = document.querySelector('#warning');
console.log(el.style.display)
My code returns "" empty string for #warning's displaystyle but it's actually "none".
I've the following HTML:
<div id="warning">
warning warning warning.
</div>
I've the following CSS:
#warning {
display: none;
}
Any ideas?
You are doing everything right for the most part, but what you are running into is a hangup for most people when they try this for the first time.
The style object in javascript is looking for this value to be inside the actual element (inline) and does not look for it in css code directly.
To access the style, the style has to exist in the dom. You could look into Window.getComputedStyle()
I hope this explains why you are reaching this roadblock.
If you know the element is an ID I'd suggest you use the getElementById(); function. Also AFAIK the style method gets inline styles only. I'd suggest using getComputedStyle();.
Code
var myDiv = document.getElementById("myDiv");
alert(getComputedStyle(myDiv).display);
Will output "none".
Example
http://jsfiddle.net/43jLLd5L/
Reading Material
Not directly related to your question but the answer has some good points.
With this fiddle http://jsfiddle.net/mungbeans/f2ne6/2/
why is the opacity undefined when accessed in js when its defined in the css?
I presume the answer is because the style is also undefined, why is that, does the style need adding somewhere explicitly before the opacity can be defined?
EDIT
the lack of [] is a typo created as I copied from source to fiddle. The style/opacity problem still exits in the original code which is correct in that aspect.
title.style.opacity
should be:
title[0].style.opacity
since getElementsByTagName returns a nodeList.
EDIT:
This still doesn't get the value. You'll need to do the following:
window.getComputedStyle(title[0]).opacity
https://developer.mozilla.org/en-US/docs/DOM/window.getComputedStyle?redirectlocale=en-US&redirectslug=DOM%3Awindow.getComputedStyle
DEMO: http://jsfiddle.net/f2ne6/12/
For two reasons:
getElementsByTagName() returns a list of elements, not a single element as getElementById(). Thus, you need to subscript the resulting NodeList to get the required DOM element;
Most importantly, when you access the styles through the style property of the element, you'll only get the inline styles, not the ones that you assign through a CSS class.
To get the computed styles, you could use window.getComputedStyle(), which will give you the final used values of all the CSS properties of the element:
alert(window.getComputedStyle(title).opacity);
DEMO.
Unfortunately, getComputedStyle is not available in IE < 9, but you can easily find a polyfill, such as this one.
It's because the style property of an HTML element (in the DOM) does not contain the computed style, it contains the immediately defined style of the element. Consider the following HTML:
<div id="one" style="width: 50px;"></div>
If you call document.getElementById("one").style.width, you'll get "50px" back. However, if you remove the style attribute and instead use CSS to style the div to have a width of 50 pixels, it will return "". You can see this in action here:
http://jsfiddle.net/aAbJY/
You're probably looking for the computed style, which can be obtained in most browsers using getComputedStyle(). It doesn't work in IE until IE9, though there's probably a way to do it in IE<9. The computed style will return the opacity no matter where it's defined. See an updated example with getComputedStyle() here:
http://jsfiddle.net/aAbJY/1/
Chase is correct, but there's another problem in your code. The style property only contains styles that were set with the style attribute of the element, so Chase's solution will only go halfway to fixing your problem. What you want to do is use the getComputedStyle() function to get the runtime style of your element:
function test(id) {
var listElement = document.getElementById(id);
var titles = listElement.getElementsByTagName("div");
var style = getComputedStyle(titles[0]);
alert( "Opacity: " + style.opacity );
}
See my updated jsfiddle here: http://jsfiddle.net/7vQ4A/1/
I have a problem - I want to DELETE the div's rather than just hide them with css on my web page. I'm newbie in Javascript and I can not say for sure whether this is but I think that should be used function removeChild(). Here's the script:
http://jsbin.com/ufoyor/edit#javascript,html/
It works like this:
1) "X" button hide pronto and crossClose divs due to the fact-purpose style of "hidden" these blocks.
2) The script sets a specific value in a cookie if the value matched the block is not shown (with style = "visibility: hidden;").
Yes, you can remove the element together with its subtree with removeChild().
However, for I suggest setting style display: none. It won't display at all (won't occupy the space as visibility:hidden does).
In plain JavaScript use removeChild(): https://developer.mozilla.org/En/DOM/Node.removeChild
In jQuery you have method remove(): http://api.jquery.com/remove/
using that code i am able to find tag display propery
but i want to get all the tag which have their display property none.Give me the result using javascript or jquery
document.getElementById('MSO_ContentTable').style.display
MSO_ContentTable is an id of div tag
$('div').filter(function() {
return $(this).css('display') == 'none'; //or whatever you want to filter.
})
See it in action.
$(':hidden')
That should do just fine for you.
Using jQuery you can try the below code to find all the elements which are hidden on the page
$("*").is(":hidden").not("input:hidden");
If a jquery solution is okay you could do:
$('*:not(:visible)')
this returns a collection of all non visible objects in the dom.
These are elements that:
They have a CSS display value of none.
They are form elements with type="hidden".
Their width and height are explicitly set to 0.
An ancestor element is hidden, so the element is not shown on the page
You could filter out only those with "display:none" by iterating on them
Try this code :
$("#MSO_ContentTable").css("display","none");
Using Jquery ,
All document by id "MSO_ContentTable" is Gone ....
In the past we used the CSS attribute "display" to show and hide DOM elements. To check if an element is visible, we could just use:
element.offsetWidth > 0
Since we had some problems with Flash and Java Applets (they stop when they get display:none) we switched to the CSS attribute "visibility".
I am now looking for a fast and easy way to check if an element is not visible.
I have tried the following:
Checking the attribute itself on the element and and all parents => too slow
Checking the calculated style directly from the browser (element.currentStyle or window.getComputedStyle() plus getPropertyValue(style property)) => also too slow
Do you know any other way or shortcut to see if an element is visible?
use JQuery and the you can do this
var isVisible = $('#foo').is(':visible');
Remember that visibility:hidden makes an element hidden, but that element still occupies its space, which may have some unexpected consequences on the layout (it may be an advantage as well if you are aware of this).
I would use absolute positioning to move the element far to the left, outside possible screen width. This gets the element out of the flow so the hidden element has no impact on layout, makes the element practically invisible, and it doesn't have the disatvantages of display:none.
.hide {
position:absolute;
left:-3000px;
}
Then to determine if an element is hidden you can use its offsetLeft property:
if( myElement.offsetLeft < 0 ){ /* it's hidden */ }
If you need to determine if a child element is off the screen (you don't know if it's the hidden element or its child) you can use .offsetParent and a while loop, as described in PPK's Find Position article.
Toggling Element Visibility by Kent is an unobtrusive, semantically valid way of presenting content that will degrade nicely for non-CSS-aware browsers.
After the page loads completely, we crawl through the entire document tree and look for block-level elements styled with class name toggle. If we find one that says toggle closed, we immediately hide its next sibling element, by styling it with class name hidden.
When we find one, we tell it to listen for mouse clicks.
When one of our pet elements hears a click, it leaps into action, hiding (or showing) its next available sibling, the same way we did it during the initial crawl.
All three class names (toggle, closed, and hidden) are fed in at the bottom in the init call, and may be changed to any valid class name.
Also look at this DevX article which compares the Display and Visibility properties.
Checking the focus would work, either parent is visible or not.
var isVisible = true;
try{
document.getElementById("target").focus();
}catch(err){
isVisible = false;
}
It obviously should work on input or link, but for other element, I'm not sure.
I have studied the same problem before using jQuery, but that time my aim is to focus the first availabe field on a form. The resulting code is like:
$(":text:visible:enabled").filter(function(){
return $(this).parents.filter(function(){
return this.style.display == "none";
}).size()==0;
}).slice(0,1).focus();
It would also work for hidden/invisble parent.
CSS selectors are optimised to find sets of matching elements. There are several libraries implementing this functionality. JQuery, ExtJS Core to name a couple.
Using Ext Core, I could write a javascript function that checks for visibility as follows:
// Checks whether the element is currently visible using
// both visibility and display properties
if(Ext.get(el).isVisible()){
alert('it\'s visible');
};
see http://extjs.com/products/extcore/docs/?class=Ext.Element for more Ext Core Ext.Element functionality.
function isVisible(elem) {
return elem.style.visibility !== "hidden";
}