javascript, <form> 태그와 구성요소에 대한 객체 생성, 접근

infoqoch·2021년 2월 19일

HTML/CSS/JavaScript

목록 보기
2/5

서버에서 클라이언트로의 통신에 있어서 데이타를 송수신하기 위한 가장 중요한 매개체는 역시 form과 그에 딸린 input, select 등이 있을 것이다. 그런데 해당 값을 호출하고 추출하는 방식은 태그 마다 다르다. 그래서 햇갈리는 경우가 많은데, 이를 정리하고자 한다.
참고로, 이러한 객체의 접근방식을 문서객체모델(DOM Document Object Model)이라고 한다. 브라우저 내에 html 페이지를 document라고 하며, javascript가 해당 html을 객체화하고 조작하고 분석하며 출력하는 전체적인 과정을 의미한다.
이번에는 javascript를 먼저 정리하고 차후 jquery를 정리하고자 한다. form 이외에 다른 부분도 향후 추가할 예정이다. 그 종류가 다양하고, jquery와 바닐라 간의 방법도 상이한데, 공부를 해도 해도 다시 까먹어서(....)

  1. document에 접근하는 방법
  • script 태그 블럭 안에서 javascript의 명령을 실행한다. 한편, 브라우저는 위에서 아래로 읽으므로 그 위치에 따라 인식여부가 결정되기도 한다. 그러한 한계를 해소하기 위하여 보통 스크립트의 명령은 이벤트처리를 하며 그 방법은 아래와 같다. 아래의 방법은 html을 모두 출력한 후에 해당 블럭을 실행하겠다는 의미이다.
    -> 자바스크립트 : window.onload = function(){}
    -> 제이쿼리 : $(document).ready(function(){})
<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>
  1. selector / element 객체 선언, 태그의 속성 부여 및 추출
  • selector의 경우 body, header, h1, span 등 html에서 기본적으로 제공하는 태그를 의미한다.
    -element의 경우 사용자가 지정하는 id, name, class 등을 의미한다.
    -id는 유일무이한 객체로서 단 하나의 태그에만 선언할 수 있다.
    -name/class는 다수의 태그에 선언할 수 있으며, 각각의 객체의 값을 선언할 때는
  • querySelector는 해당하는 객체가 여러개라 하더라도 단 하나만 적용되며, 그것은 document에서 처음으로 출력되는 객체이다.
  • selectorAll의 경우 해당하는 모든 객체에 적용된다.
  • 속성 부여와 추출은 setAttribute / getAttribute를 통해서도 가능하며, 그 이외에 다양한 방법이 존재한다.
<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>
  1. 문서 객체 내부의 글자로서 html과 text의 선언
  • textContent의 경우 순수한 text/plain 형태이며, innerHtml은 text/html 형태로서 html의 형태로 렌더링된다.
  • textContent와 innerHTML의 경우 기존의 값을 덮어쓴다. 만약 추가하고 싶을 경우 =이 아닌 += 를 사용한다.
  • 값을 추출하는 방법은 .textContent만 선언하면 된다.
<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>
  
profile
JAVA web developer

0개의 댓글