🚀 자바 스크립트 JavaScript
1️⃣3️⃣ 자바 스크립트 - Dom이란? + childNodes, nodeList, appendChild, insertChild 정리
Meteora_
2021. 3. 4. 17:21
728x90
Dom 이란? (Document Object Model)
각 태그를 접근하기 위한 Object(객체)
그 Object를 접근하기 위한 함수
코드 펼치기 ->
더보기
<!DOCTYPE html>
<html> <!-- root tag -->
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- DOM : Document Object Model
각 tag를 접근하기 위한 Object(객체)
그 Object를 접근하기 위한 함수 -->
<!-- childNodes -->
<h3 id="intro">h3 tad id intro</h3>
<p id="demo">p tag id demo</p>
<button type="button" onclick="func()">버튼</button>
<script type="text/javascript">
function func(){
//let text = document.getElementById('intro').childNodes[0].nodeValue;
let text = document.getElementById('demo').childNodes[0].nodeValue;
alert(text);
}
</script>
<br><br>
<select id="car">
<option>벤츠</option>
<option>BMW</option>
<option>아우디</option>
</select>
<button type="button" onclick="cars()">자동차 선택</button>
<script type="text/javascript">
function cars(){
let carName = document.getElementById("car").childNodes;
alert(carName[1].text); //태그로 번지수를 따지기때문에 벤츠 1번지 / 벤츠 옵션 밖 2번지 / BMW 3번지
}
</script>
<br><br>
<!-- appendChild(뒤에 추가), insertChild(앞) -->
<div id="div1">
<p id="p1">첫번째 p태그</p>
<p id="p2">두번째 p태그</p>
</div>
<button type="button" onclick="appendfunc()">뒤에추가</button>
<button type="button" onclick="insertfunc()">앞에추가</button>
<button type="button" onclick="delectfunc()">삭제</button>
<script type="text/javascript">
function appendfunc(){
let ptag = document.createElement('p'); // <p></p> 추가
let textNode = document.createTextNode("새로운 p 태그"); // <p>안에 해당 문자열추가
ptag.id= 'newid'; //새로 생긴 객체
ptag.className= 'newclass'; // 다시보기
ptag.appendChild(textNode); //<p>새로운 태그</p> 추가완료
let element = document.getElementById("div1");
element.appendChild(ptag);
}
function insertfunc(){
let h3tag = document.createElement('h3'); // <h3></h3> 추가
let textNode = document.createTextNode("새로운 h3태그"); // <h3>안에 해당 문자열추가
h3tag.appendChild(textNode);
let element = document.getElementById("div1");
let elementBefore = document.getElementById("p2"); // p2 앞에다 추가할거야 (추가할 위치 설정)
element.insertBefore(h3tag, elementBefore);
}
function delectfunc(){
let element = document.getElementById("div1");
let removeElement = document.getElementById("p2"); // 지우고 싶은 id값
element.removeChild(removeElement); //removeChild 함수로 지우고 싶은 객체 삭제
//새로 추가하는 객체 삭제 +
}
</script>
<!-- NodeList -->
<p>Hello</p>
<p>World</p>
<p>I can do it</p>
<p>Never Change My Mind</p>
<button type="button" onclick="listfunc()">Nodelist</button>
<script type="text/javascript">
function listfunc() {
let nodelist = document.getElementsByTagName("p");
alert(nodelist.length);
nodelist[3].innerHTML = "안녕하세요";
for (i = 0; i < nodelist.length; i++) {
nodelist[i].style.backgroundColor="#00ff00";
}
}
</script>
</body>
</html>