I am trying to get the value of "display" through JS sorted by Classes. My code is:
var x = document.getElementsByClassName("codeContainer");
alert(x[0].style.display);
The thing is that the alert box is just empty. The call
alert(x.length);
works great and returns "4". What am I doing wrong? Thanks very much!
Problem is, if the element is formatted by external css instead of inline css using style attribute, you are bound to get blank value.
alert(x[0].style.display);
With inline css:
var inputs = document.getElementsByTagName('input'); console.log('total inputs:', inputs.length); var bg = inputs[0].style.background; console.log('background:', bg);
<input type='text' style='background:orange' />
You need to get the computed style for the same, getStyle() reference .
var getStyle = function(el, cssprop) { if (el.currentStyle) //IE return el.currentStyle[cssprop] else if (document.defaultView && document.defaultView.getComputedStyle) //Firefox return document.defaultView.getComputedStyle(el, "")[cssprop] else //try and get inline style return el.style[cssprop] } var inputs = document.getElementsByTagName('input'); console.log('total inputs:', inputs.length); console.log('color:', getStyle(inputs[0], 'color'));
.input { color: blue; }
<input type='text' class='input' value='hi' /> <input type='text' class='input' value='hello' />
The property "style.display" is not defined. therefore it returns "empty"
You can try this:
alert(x[0].style.display||window.getComputedStyle(x[0],null).getPropertyValue("display"));
after the DOM is ready only we should check for the properties. please check the code below.
(function(){var x = document.getElementsByClassName("codeContainer");
alert(x[0].style.display);})();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.