Uncaught TypeError: .appendChild is not a fuction 에러 해결
다음과 같은 html 문서를 작성했다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
html {
padding: 0px;
margin: 0px;
}
body {
background-color: black;
text-align: center;
}
section {
width: 50%;
margin: 50px auto;
background-color: brown;
border-radius: 20px;
padding: 20px;
}
img {
z-index: 100;
will-change: opacity;
}
h1,
h3,
span {
color: white;
}
</style>
</head>
<body>
<section>
<img src="img/Jeong.jfif" alt="avatar" />
<h1 id="brand">Goood Coding</h1>
<h3>'O' between the god and the good</h3>
</section>
<span>Hello World!</span>
<script>
</script>
</body>
</html>
여기서 우선 section 태그를 잡아오고, creatElement를 활용해 h2 태그를 생성하고, 이를 section에 삽입할 생각으로 script에 다음과 같은 코드를 작성하였다.
<script>
const section = document.querySelectorAll('section');
const h2 = document.createElement('h2');
h2.setAttribute('class', 'title'); //<h2 class="title"></h2>
h2.textContent = "This is a title"; //<h2 class="title">This is a title</h2>
section.appendChild(h2); //Uncaught TypeError: section.appendChild is not a fuction 에러 출력!//
</script>
에러 로그와 함께 'This is a title' 문구가 정상적으로 출력되지 않는 현상 발생,
처음엔 크롬이 버전이 낮아서 appendChild를 지원하지 않는건가 싶어서
크롬도 재설치하고 별별 쑈를 했으나.. 해답은 간단했다.
querySelectorAll이 아니라 querySelector로 section을 불러와야 했던 것!
바꿔주니 바로 정상적으로 동작한다.
이러한 문제가 발생하는 이유는 바로,
querySelectorAll API가 Array를 반환하기 때문!
<script>
const section = document.querySelector('section');
const h2 = document.createElement('h2');
h2.setAttribute('class', 'title'); //<h2 class="title"></h2>
h2.textContent = "This is a title"; //<h2 class="title">This is a title</h2>
section.appendChild(h2);
</script>
해결 완료!
Author And Source
이 문제에 관하여(Uncaught TypeError: .appendChild is not a fuction 에러 해결), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@nasowoo/Uncaught-TypeError-.appendChild-is-not-a-fuction-에러-해결저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)