Navneet Saini
Navneet Saini

Reputation: 944

JavaScript: not able to alert output value

The code is pretty simple.

HTML:

<div class="simpleDiv" id="Child1" onmouseover="expandDiv(this);"></div>

CSS:

.simpleDiv {
    background-color: red; 
    width: 100px; 
    height: 50px; 
    margin: 5px; 
    margin-left: 50px; 
    opacity: 1;
}   

JavaScript:

function expandDiv(object){
    alert(document.getElementById(object.id).style.height);
} 

Why am I not able to alert the height of the div like this? If I alert the id or class using the function hasAttribute, thats working fine but not able to alert the css properties of the elements.

Any help appreciated!

Upvotes: 0

Views: 127

Answers (4)

KdR135
KdR135

Reputation: 11

Use JQuery:

 alert($('#Child1').css("height");

Or to change the attribute, use:

$('#Child1').css("height", value )

Ignore if you don't want JQuery.

Upvotes: 1

user2188149
user2188149

Reputation:

function expandDiv(object){



    alert(document.getElementById(object.id).innerHeight);

}

Upvotes: 2

mbochynski
mbochynski

Reputation: 706

try using:

alert(document.getElementById(object.id).offsetHeight);

Here is description: offsetHeight on MDN

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324630

Why not just alert(object.style.height)?

Anyway, the reason it doesn't work is because elem.style.property only works with inline style="..." attributes. To take into account all styles, you need this:

alert(window.getComputedStyle(object).height)

Older versions of IE don't support this, but it's a very easy shim:

window.getComputedStyle = window.getComputedStyle || function(e) {return e.currentStyle;};

Upvotes: 6

Related Questions