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
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:
getElementById()
. Thus, you need to subscript the resulting NodeList
to get the required DOM element;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/