본문 바로가기

javaScript

[javaScript] div(p1), div(p2) 추가 및 checkbox 선택하여 이름 나태기

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>Insert title here</title>

</head>


<body>



<h1 id="intro">여기가 h1태그</h1>

<p id="demo">여기가 p태그</p> 


<button onclick="myfunc()">클릭</button>


<script type="text/javascript">

function myfunc() {

var mytext = document.getElementById("intro").childNodes[0].nodeValue;

document.getElementById("demo").innerHTML = mytext;

}

</script>


<div id="div1">

<p id="p1">div p1</p>

<p id="p2">div p2</p>

</div>



<!-- appendChild : JS에서 새로운 태그를 추가 -->

<button onclick="myfunc1()">div태그에 추가</button>


<script type="text/javascript">

function myfunc1() {

var para = document.createElement("p"); // <p></p>

var node = document.createTextNode("새로운 p 태그");

para.appendChild(node); // <p>새로운 p 태그</p>

var element = document.getElementById("div1");

element.appendChild(para);

}

</script>



<!-- insertBefore : JS에서 새로운 태그를 추가 -->

<button onclick="myfunc2()">지정태그 앞에 추가</button>


<script type="text/javascript">

function myfunc2() {

var para = document.createElement("pre"); // <p></p>

var node = document.createTextNode("새로운 pre 태그");

para.appendChild(node); // <p>새로운 p 태그</p>

var element = document.getElementById("div1");

var child = document.getElementById("p2");

element.insertBefore(para, child);

}


</script>


<!-- removeChild : JS에서 태그를 삭제 -->

<button onclick="myfunc3()">삭제</button>


<script type="text/javascript">

function myfunc3() {

var parent = document.getElementById("div1");

var child = document.getElementById("p1");

parent.removeChild(child);

}

</script>


<br><br>


<select id="mySelect" size="4">0

<option>1 아우디</option>2

<option>3 BMW</option>4

<option>5 Volvo</option>6

<option>7 Saab</option>8

</select>9


<br><br>


<p id="carname">자동차 명</p>


<button onclick="myfunc4()">자동차선택</button>


<script type="text/javascript">

function myfunc4() {

var cnum = [1, 3, 5, 7];

var cho = document.getElementById("mySelect").selectedIndex;

var node = document.getElementById("mySelect").childNodes;

// alert("cho = " + cho); // Object가 넘어온다

// alert("선택 = " + node[cho + 1].text); // Object가 넘어온다

// document.getElementById("carname").innerHTML = node[3].text;

document.getElementById("carname").innerHTML = node[cnum[cho]].text;

}


</script>



<!-- 

<html> root tag

<head>

</head>

<body>0

<h1>1</h1>2

<p>3</p>4

</body>5

</html>

 -->


</body>

</html>





<결과>