Javascript alert getElementsByClassName("x").style.display

1.8k views Asked by At

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!

3

There are 3 answers

0
Federico On

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"));
0
Akhil On

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);})();
1
AudioBubble On

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' />