2019백업

Javascript 엘리먼트 선택방법 (3. Selector API Level1)

728x90

querySelector() 함수를 사용한 HTML 엘리먼트 선택방법

Selector API Level1 (Jquery에서 css를 지정할 수 있었는데 이제 HTML5에서 selector API 지원합니다).

 

html 코드

1
2
3
4
5
6
7
8
9
10
11
<section id ="section3">
        <h1>Ex3 : Selector API Level1</h1>
        <div>
            <input name="x" type="text" value="0" dir ="rtl">
             +
            <input class="txt-y" type="text" value="0" dir ="rtl">
            <input class="btn-add" type="button" value="=">
            <input class="txt-sum" type="text" value="0" dir ="rtl" readonly>
        </div>
</section>
<script src="selector.js">
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

 

JS코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
window.addEventListener("load"function() {
    var section3 = document.getElementById("section3");
    //css의 selector를 사용 할 수 있다.
    var txtX = section3.querySelector("input[name='x']");
    var txtY = section3.querySelector(".txt-y");
    var btnAdd = section3.querySelector(".btn-add");
    var txtSum = section3.querySelector(".txt-sum");
 
    btnAdd.onclick = function () {
        var x = parseInt(txtX.value);
        var y = parseInt(txtY.value);
        txtSum.value= x + y;
    };
});
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
 

querySelector() 함수 인자로 css 에서 사용하는 문법 (클래스, id, Form input 태그)를 넣어 html 객체를 읽어올 수 있습니다.

 

실행결과

Selector API 설명링크

https://developer.tizen.org/development/guides/web-application/w3chtml5supplementary-features/user-interface/selectors-api-level-1-and-2?langredirect=1

 

Selectors API (Level 1 and 2) | Tizen Developers

 

developer.tizen.org

 

반응형