javascript ES5 정리

js 문서의 element 객체 이용

풀스택 개발자 2020. 9. 23. 01:03

js는 코딩 순서대로 로딩이 됩니다.

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <script>
       function add(){
            var a=3;
            var b=4; 
            btnprint.value=a+b;
             update.innerText = a+b;
        }
            btnprint.onclick = add;
     </script>

     
</head>
<body>
    
    <input type="button" value="클릭" id="btnprint"/></br>
    <span id="update">하이요</span>
</body>
</html>

 

다음과 같이 코드를 작성하였다.

id가 btnprint인 객체를 클릭하면 add함수가 실행되어 id update 의 innerText를 변경하는 내용이다.

 

하지만

 

이코드는 제대로 실행되지 않는다. 그 이유는? 코드 순서상 script가 모두 읽어진후 html부분이 읽혀지기 때문에 click을 해도 아무런 이벤트가 실행되지 않는다.

 

그럼 해결 방안은?

 

script부분은 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>
  
</head>
<body>
    
    <input type="button" value="클릭" id="btnprint"/></br>
    <span id="update">하이요</span>
</body>
<script>
    function add(){
         var a=3;
         var b=4; 
         btnprint.value=a+b;
          update.innerText = a+b;
     }
         btnprint.onclick = add;
  </script>
</html>

이런식으로

 

하지만 또 다른 방법이 존재한다.

window의 onload 객체를 사용하여 window창(브라우저 창)을 모두 읽은후 해당 함수를 실행하게 하는 법이다.

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
        function add(){
             var a=3;
             var b=4; 
             btnprint.value=a+b;
              update.innerText = a+b;
         }
         function init(){
            btnprint.onclick = add;
        }
        window.onload = init;
      </script>
</head>
<body>
    
    <input type="button" value="클릭" id="btnprint"/></br>
    <span id="update">하이요</span>
</body>

</html>

 

이런식

 

하지만 이건 잘못된 스크립트 작성 방식이다 해당id의 객체를 읽을때 이런식으로 읽으면 안된다.

getElmentById를 사용하여 id를 읽어와야한다.

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
        function add(){
             var a=3;
             var b=4; 
             btnprint.value=a+b;
              update = document.getElementById("update");
              update.innerText = a+b;
         }
         function init(){
            btnprint = document.getElementById("btn-print");
            btnprint.onclick = add;
        }
        window.onload = init;
      </script>
</head>
<body>
    
    <input type="button" value="클릭" id="btn-print"/></br>
    <span id="update">하이요</span>
</body>

</html>

 

이 방식이 정식 방식이다.