6

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>'

CaringDev
  • 8,391
  • 1
  • 24
  • 43
Rajesh Kumar
  • 153
  • 2
  • 4
  • 13

2 Answers2

4

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';
Kirill
  • 2,590
  • 1
  • 17
  • 16
Bhabani P
  • 1,061
  • 7
  • 4
  • I tried all the ways in javascript not working in typescript. please suggest me any way to get and update height in typescript. – Rajesh Kumar Jan 17 '17 at 06:43
  • var result = document.getElementsByClassName('height')[0]; var wrappedResult = angular.element(result); wrappedResult.css('height', '100px'); – Bhabani P Jan 17 '17 at 06:48
1

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 older targets and browsers this collection needs to be enumerated with an old-school for loop. For newer targets (>= ES6) and browsers, see this answer.
  • the elements of the collection are of type Element but style is defined on HTMLElement. Luckily TS automatically narrows a type in the scope of a type guard.
Community
  • 1
  • 1
CaringDev
  • 8,391
  • 1
  • 24
  • 43