ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 웹브라우저 자바스크립트 - 속성 API
    JavaScript/생활코딩 2018. 11. 27. 15:59



    속성 API - https://opentutorials.org/course/1375/6683



    속성 API는 <a id="target" href="http://opentutorials.org">opentutorials</a> 이 부분에서 id, href 와 같은 속성을 제어할 수 있다.



    <!DOCTYPE html>

    <html>

    <body>

    <a id="target" href="http://opentutorials.org">opentutorials</a>

    <script>


    var t = document.getElementById('target');


    console.log(t.getAttribute('href')); //http://opentutorials.org


    t.setAttribute('title', 'opentutorials.org'); // title 속성의 값을 설정한다.


    console.log(t.hasAttribute('title')); // true, title 속성의 존재여부를 확인한다.


    t.removeAttribute('title'); // title 속성을 제거한다.


    console.log(t.hasAttribute('title')); // false, title 속성의 존재여부를 확인한다.


    </script>

    </body>

    </html>


    위의 예제에서 실행한 코드들의 결과를 통해 속성을 제어하는 방법을 알 수 있다.

    • t.getAttribute('href') : getAttribute는 속성을 가져오는 역할로 href를 적으면 http://opentutorials.org 값이 반환된다.
    • t.setAttribute : setAttribute는 속성값을 설정하는 역할이다.
    • t.hasAttribute('title') : hasAttribute는 속성의 존재여부를 확인한다.
    • t.removeAttribute('title') : removeAttribute는 해당 속성을 삭제한다.








    속성과 프로퍼티

    속성과 프로퍼티의 차이점을 알아야 한다.


    속성방식

    html의 속성명을 그대로 가져와서 실수할 일이 없지만 처리속도가 약간 느리다.

    target.setAttribute('class', 'important');


    프로퍼티방식

    html의 속성명과 자바스크립트로 제어시 사용하는 명칭이 다를 수 있다.

    사용하기 편리하고 빠르다.

    target.className = 'important';


    아래는 프로퍼티방식을 사용할 때 자바스크립트로 제어시 사용하는 명칭이 다른 것들이다.

    classclassName
    readonlyreadOnly
    rowspanrowSpan
    colspancolSpan
    usemapuserMap
    frameborderframeBorder
    forhtmlFor
    maxlength

    maxLength




    그리고 속성방식과 프로퍼티방식을 사용할 때 결과값이 다를 수도 있다.


    <a id="target" href="./demo1.html">ot</a>

    var target = document.getElementById('target');



    console.log('target.getAttribute("href")', target.getAttribute("href")); //속성방식, 결과값은 직접기술한 ./demo1.html 이 나온다.

    console.log('target.href', target.href); //프로퍼티방식, 결과값은 상대경로가 아닌 전체경로가 모두 보인다.








    댓글

Designed by Tistory.