Typescript for DOM manipulation
If you want to manipulate DOM by using typescript I think this blog is helpful. In typescript, you need to assign a variable type. I try some manipulation below:
1. Get an element by id.
<body>
<h1 id=”element”>Hello World!</h1>
</body>
Here an id name element. If you want to get it with typescript you use this:
<HTMLElement>document.getElementById(‘element’);
You can put it into a variable like:
const element:HTMLElement = <HTMLElement>document.getElementById(‘element’);
You need to define which type of item you put into it. If we get an element by id we get a html element. For this reason we need to define it as HTMLElement.
2. Get elements by class name:
<body>
<div class=”box”>Box1</div>
<div class=”box”>Box2</div>
<div class=”box”>Box3</div>
<div class=”box”>Box4</div>
</body>
Here are four different divs with the same class box. We want to get these items.
const boxes:HTMLCollectionOf<Element> = document.getElementsByClassName(‘box’);
We know that if we get elements by class name it will return a HTML collection. Which is an array-like object.
So that we need to define its variable with HTMLCollectionOf<Element>
3. Compare innerText with number:
To compare html element innertext you need to convert it a number otherwise you cannot compare with a number.
<body>
<h1 id=”element”>56</h1>
</body>
const element = <HTMLElement>document.getElementById(‘element’);
if(element.innerText < 60)
In javascript, we can compare like that but in typescript, we can’t. Because element.innerText is a string. We can’t compare a string with a number. So we need to convert one of them to another.
if(element.innerText < ‘60’)
Or,
if(+element.innerText < 60)
First ex. 60 is converted to a string and the second ex. element.innerText value is converted to a number with + sign.
If you want mathematical operations like ( + , — , * , / , % ) etc. you need to follow the same way.
This for today.