According to this question page and the accepted answer here, the right way to get inherited CSS values via Javascript is getComputedStyle()
. However, that does not work in the following example:
<!DOCTYPE html>
<html lang="en">
<body>
<form id="iterateThroughMe">
<div class="notHidden"><input name="myNum" type="number" /></div>
<div><input name="myOtherNum" type="number" /></div>
<input name="myText" type="text" />
<div id="hider" style="display: none;">
<input name="hiddenElement" type="number" />
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
var inputs = $("#iterateThroughMe").find('input');
for(var i = 0; i<inputs.length; i++) {
var displayStyle = window.getComputedStyle(inputs[i], null).display;
console.log(
(($(inputs[i]).is(":hidden"))?"in":"")+
"visible element: ",inputs[i],"has display style",displayStyle);
}
</script>
</body>
</html>
Saved and opened in a browser, the following is visible on the console:
visible element: <input name="myNum" type="number"> has display style inline-block
visible element: <input name="myOtherNum" type="number"> has display style inline-block
visible element: <input name="myText" type="text"> has display style inline-block
invisible element: <input name="hiddenElement" type="number"> has display style inline-block
There is a specific way to access hidden/visible status in jQuery, noted here, which works in the example above but is not always appropriate. Why does getComputedStyle not distinguish between hidden and non-hidden elements, producing inline-block
on all four lines instead of none
at the end of the output?