서버에서 클라이언트로의 통신에 있어서 데이타를 송수신하기 위한 가장 중요한 매개체는 역시 form과 그에 딸린 input, select 등이 있을 것이다. 그런데 해당 값을 호출하고 추출하는 방식은 태그 마다 다르다. 그래서 햇갈리는 경우가 많은데, 이를 정리하고자 한다.
참고로, 이러한 객체의 접근방식을 문서객체모델(DOM Document Object Model)이라고 한다. 브라우저 내에 html 페이지를 document라고 하며, javascript가 해당 html을 객체화하고 조작하고 분석하며 출력하는 전체적인 과정을 의미한다.
이번에는 javascript를 먼저 정리하고 차후 jquery를 정리하고자 한다. form 이외에 다른 부분도 향후 추가할 예정이다. 그 종류가 다양하고, jquery와 바닐라 간의 방법도 상이한데, 공부를 해도 해도 다시 까먹어서(....)
<script type="text/javascript">
// document.getElementById("a").style.border = "solid black 1px"; // body 보다 위에 있어서 <div id ="a">가 생성되기 전에 id = a를 호출하였음. 그러므로 작동하지 아니함.
window.onload = function (){
document.getElementById("a").innerHTML = "hello, js!"
document.getElementById("a").style.color = "red";
}
$(document).ready(function(){
$('#b').css("color", "blue").html("hello, jq!");
});
</script>
<body>
<div id="a"></div>
<br>
<div id="b"></div>
</body>
<script type="text/javascript">
window.onload = function () {
document.getElementById("idA").style.color = 'red';
document.getElementById("idB").style.color = 'blue';
var nameAList = document.getElementsByName("nameA");
for(var i=0; i<nameAList.length; i++){
nameAList[i].style.textDecoration='underline';
}
var nameBList = document.getElementsByName("nameB");
for(var i=0; i<nameBList.length; i++){
nameBList[i].style.textDecoration='line-through';
}
var classAList = document.getElementsByClassName("classA");
for(var i=0; i<classAList.length; i++){
classAList[i].style.fontStyle='italic';
}
var classBList = document.getElementsByClassName("classB");
for(var i=0; i<classBList.length; i++){
classBList[i].style.fontWeight='bold';
}
var selectorAllList = document.querySelectorAll('h3');
for(var i=0; i<selectorAllList.length; i++){
selectorAllList[i].style.border ="1px red solid";
}
document.querySelector('h3').style.border ="5px black solid";
var str = document.querySelector('h3').getAttribute('style');
alert(str);
}
</script>
<script type="text/javascript">
window.onload = function () {
alert("이전 값 : " + document.getElementById("idB").textContent);
document.getElementById("idA").innerHTML = "<h3>hello</h3>"
document.getElementById("idB").textContent = "<h3>hello</h3>"
document.getElementById("idB").textContent += "<h3>HELLO</h3>"
alert("이후 값 : " + document.getElementById("idB").textContent);
}
</script>
<body>
<div id="idA">반가워요.</div>
<div id="idB">반가워요.</div>
</body>