Reputation: 116
I'm trying to modify an elements height (elementTwo) using another element's height (elementOne) using JS (No jQuery)
When I try logging elementOne.style.height, I get an empty string Using Safari and Chrome inspector's I can see the computed height but cannot access it using JS. It shows up as faded (See screenshots)
Screenshot of Safari inspector | Screenshot of Chrome inspector
.elementOne {
min-height: 100vh;
width:100%;
}
ElementOne has a min-height set to be 100vh but automatically increases in size based on the device / size of child elements. It does not have a height set. ElementTwo does not have any css by default
I am trying to do this using JS only and do not want to use jQuery at all.
Upvotes: 0
Views: 1484
Reputation: 1074248
If you want the height style for the element, you need to get the computed style with getComputedStyle
(or currentStyle
on old IE):
function getStyle(element) {
if (typeof getComputedStyle !== "undefined") {
return getComputedStyle(element);
}
return element.currentStyle; // Old IE
}
var heightStyle = getStyle(element).height;
That will be a string, with units on it (not necessarily the units in the CSS).
If you want the element's height, as opposed to its height
style, use element.offsetHeight
or element.clientHeight
. They will be numbers; it's the number of pixels rounded to the nearest whole number.
If you want the most precise information you can get (including a fractional number of pixels if relevant; that can happen), you'd use getBoundingClientRect
.
Example:
function getStyle(element) {
if (typeof getComputedStyle !== "undefined") {
return getComputedStyle(element);
}
return element.currentStyle; // Old IE
}
var element = document.querySelector(".foo");
var bounding = element.getBoundingClientRect();
console.log({
"height style": getStyle(element).height,
"offsetHeight": element.offsetHeight,
"clientHeight": element.clientHeight,
"bounding height": bounding.height
});
.container {
display: inline-block;
width: 100px;
height: 200px;
position: relative;
background-color: yellow;
}
.foo {
display: inline-block;
width: 100%;
height: 33.3%;
background-color: blue;
}
<div class="container">
<div class="foo"></div>
</div>
Upvotes: 3
Reputation: 691
I think you want to use the property .clientHeight
of the dom-element.
See the mdn arcticle about it.
Upvotes: 1