Accessing node list in Typescript

リン (linh)
Goalist Blog
Published in
2 min readJul 7, 2022

Okay, i know what it sounds like :)
It’s too simple to write about but I used to struggle with it.
Anyway, it’s better to admit what you don’t know and get to know it than hide your ignorance.

  • For the example, i have below piece of html
<input type="checkbox" name="test">
<label>Test2</label>
<select name="test">
<option value="city1" alias="Option.P_Working">A</option>
<option value="city2" alias="Option.P_Leaving">B</option>
<option value="city3" alias="Option.P_NoExperience">C</option>
</select>
<input type="radio" id="1" name="test" value="D">
<label>Test1</label><br>
<input type="text" name="test">
  • Then I get all the elements with name “test” withdocument.getElementByName and console log the results as below. Here, you can see the node list and it’s properties (like value, attributes,…)
  • But when you loop this list and console.log each item, it would be like below. You’ll get only the tag name and may ask yourself: “where are the properties we saw above? Where?”
  • Okay, that’s when type casting come to rescue 🦸
    You can type cast using “as”. Here’s the document you can check out: https://www.w3schools.com/typescript/typescript_casting.php
  • When looping the nodelist, we need to cast the type “as” an element to be able to access it’s properties. Like this
nodeList.forEach((el) => {
const element = el as HTMLInputElement;
// after that, we can access the properties
console.log(element.value)
})

That’s it, guys! 🙏
See you in another post

--

--

リン (linh)
Goalist Blog

A career-changed-non-tech-background point of view.