Home [TypeScript] 타입스크립트 Html 조작시 타입지정
Post
Cancel

[TypeScript] 타입스크립트 Html 조작시 타입지정


문제 발생

  • className이 input 요소들에 color를 바꾸려는데 에러 발생
1
2
const input = document.querySelectorAll(".input");
input.style.color = "red";

Error: style부분에서 발생 - Property ‘style’ does not exist on type ‘NodeListOf <Element >’ .ts(2339)

처음에는 className으로 추출한 input변수가 배열이라서 그런 줄 알았다. 배열로 된 Html 조작은 반복문으로 하나하나 바꿔주어야 하니까 그래서 0번쨰 input만 바꾸기 시도

1
2
const input = document.querySelectorAll(".input");
input[0].style.color = "red";

Error: style부분에서 발생 - Property ‘style’ does not exist on type ‘Element’.ts(2339)

바뀐 에러 내용상 타입이 Element가 아니라서 style 속성을 사용할 수 없다고 한다.


해결

  • NodeListOf: 추출한 Html 요소가 배열일떄 지정해주는 type
  • <>안에 들어가는 내용은 NodeListOf 안에 내용은 어떤 타입인지 알려주면 된다, 나는 지금 Html 요소라고 말해준 것 이다.
1
2
const input:NodeListOf<HTMLElement> = document.querySelectorAll(".input");
input[0].style.color = "red";

하지만 input 태그에 속성 중 하나인 focus() 함수는 에러를 일으킨다 일반 Html 요소라고 지정해준 타입으로는 focus() 속성을 쓸 수 없는 것 이다. 태그에 따른 타입을 알아보자

Html 태그 타입

input

  • HTMLInputElement
1
const input:NodeListOf<HTMLInputElement> = document.querySelectorAll(".input");

a

  • HTMLAnchorElement
1
const a:NodeListOf<HTMLAnchorElement> = document.querySelectorAll(".a");

button

  • HTMLButtonElement
1
const button:NodeListOf<HTMLButtonElement> = document.querySelectorAll(".button");

h1

  • HTMLHeadingElement
1
const h1:NodeListOf<HTMLHeadingElement> = document.querySelectorAll(".h1");

img

  • HTMLImageElement
1
const img:NodeListOf<HTMLImageElement> = document.querySelectorAll(".img");

마치며

혹시 잘못된 정보나 궁금하신 게 있다면 편하게 댓글 달아주세요.
지적이나 피드백은 언제나 환영입니다.

This post is licensed under CC BY 4.0 by the author.