0

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!

4 Answers 4

6

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;};
Sign up to request clarification or add additional context in comments.

1 Comment

Even if I try alert(object.style.height) , it doesn't work! Does it? Thanks for the answer, by the way. the second one works!
2
function expandDiv(object){



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

}

Comments

1

try using:

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

Here is description: offsetHeight on MDN

Comments

1

Use JQuery:

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

Or to change the attribute, use:

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

Ignore if you don't want JQuery.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.