Please suggest me any way to get and update the height of a HTML element in typescript.
document.getElementsByClassName('height').style.height = childHeight;
is not working. I get
Property 'style' does not exist on type 'HtmlCollectionOf<Element>'
We use css property height: calc( 100% - div_height ); Here, Calc is a function. It uses mathematical expression by this property we can set the height content div area dynamically.
This seems like the ideal candidate for transition from a table-based layout to a CSS layout. It makes sense: both DIVs and tables can be nested, have HEIGHT and WIDTH attributes set, contain borders, etc.
How to get the <div> height using JavaScript ? Method 1: Using the offsetHeight property: The offsetHeight property of an element is a read-only property and used to return the height of an element in pixels. It includes any borders or padding of the element.
CSS Setting height and width The height and width properties are used to set the height and width of an element. The height and width properties do not include padding, borders, or margins. It sets the height/width of the area inside the padding, border, and margin of the element.
We can also use the jQuery height () and width () methods to get the height and width of the element. This height and width do not include border, padding and margin. Let’s see how we can return the height and width of a <div> element.
The jQuery innerHeight () and innerWidth () methods get the inner height and width of an element. Inner height and width include padding.
One problem here might be that getElementsByClassName
returns an array of elements with class height
. To apply style
method you need to have one element.
This code will apply 10px height to the first such element:
document.getElementsByClassName('height')[0].style.height = '10px';
First, the code you are after:
const cnElems = document.getElementsByClassName("cn");
for (let i = 0; i < cnElems.length; i++) {
const e = cnElems[i];
if (e instanceof HTMLElement) {
e.style.height = "10px";
}
}
Then, an explanation... There are two main obstacles here:
getElementsByClassName
returns a HTMLCollection<Element>
for
loop. For newer targets (>= ES6) and browsers, see this answer.Element
but style
is defined on HTMLElement
. Luckily TS automatically narrows a type in the scope of a type guard.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With