myDiv.style.display returns blank when set in master stylesheet
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
Bootstrap Collapsed div initial display property is empty
This is standard via the method you are using. document.getElementById('element').style.display
only checks the styles that live on the element and since no display style lives on that element it is returning ""
. To get the computed styles (i.e. from the style sheet) on an element you need to use the property getComputedStyle
(or currentStyle
for IE).
This question/answer has some really good info on the difference and a good function for how to check:
myDiv.style.display returns blank when set in master stylesheet
How to use Javascript to check and load CSS if not loaded?
Just check to see if a <link>
element exists with the href
attribute set to your CSS file's URL:
if (!$("link[href='/path/to.css']").length)
$('<link href="/path/to.css" rel="stylesheet">').appendTo("head");
The plain ol' JS method is simple too, using the document.styleSheets collection:
function loadCSSIfNotAlreadyLoadedForSomeReason () {
var ss = document.styleSheets;
for (var i = 0, max = ss.length; i < max; i++) {
if (ss[i].href == "/path/to.css")
return;
}
var link = document.createElement("link");
link.rel = "stylesheet";
link.href = "/path/to.css";
document.getElementsByTagName("head")[0].appendChild(link);
}
loadCSSIfNotAlreadyLoadedForSomeReason();
Related Topics
How to Get the Coordinates of a Mouse Click on a Canvas Element
Why Does Chrome Debugger Think Closed Local Variable Is Undefined
How to Highlight Text Using JavaScript
Convert Xml to Json (And Back) Using JavaScript
Programmatically Changing Webkit-Transformation Values in Animation Rules
Change Background Image in Body
Google Maps Not Rendering Completely on Page
Jquery Equivalent of Yui Stylesheet Utility
Detect the Internet Connection Is Offline
How to Add Number of Days to Today'S Date
JavaScript: Difference Between .Foreach() and .Map()
How to Read and Write into File Using JavaScript
Regex to Extract All Matches from String Using Regexp.Exec