[JavaScript] Element 객체


Element 객체


1. 소개

Element 객체는 엘리먼트를 추상화한 객체다. HTMLElement 객체와의 관계를 이해하기 위해서는 DOM의 취지에 대한 이해가 선행되야 한다. 

DOM은 HTML만을 제어하기 위한 모델이 아니다. HTML이나 XML, SVG, XUL과 같이 마크업 형태의 언어를 제어하기 위한 규격이기 때문에 Element는 마크업 언어의 일반적인 규격에 대한 속성을 정의하고 있고, 각각의 구체적인 언어(HTML,XML,SVG)를 위한 기능은 HTMLElement, SVGElement, XULElement와 같은 객체를 통해서 추가해서 사용하고 있다.


2. 다른 객체들과의 관계

DOM의 계층구조에서 Element 객체의 위치는 아래와 같다.



※ Element와 HTMLElement를 구분하는 이유

DOM이라는 것이 HTML만 제어하는 것이 아니다.--> 마크업 언어(XML, HTML, SVG 등등)< > 를 제어하기 위해 표준이 DOM이다.(마크업 언어는 Element가 있다.)

(엘리먼트가 HTML에만 있는 것이 아니다.)


3. 주요기능

(1)  식별자

문서내에서 특정한 엘리먼트를 식별하기 위한 용도로 사용되는 API

- Element.classList

- Element.className

- Element.id

- Element.tagName


(2) 조회

엘리먼트의 하위 엘리먼트를 조회하는 API

- Element.getElementsByClassName

- Element.getElementsByTagName

- Element.querySelector

- Element.querySelectorAll


(3) 속성

엘리먼트의 속성을 알아내고 변경하는 API

- Element.getAttribute(name)

- Element.setAttribute(name, value)

- Element.hasAttribute(name);

- Element.removeAttribute(name);


4. 식별자 API

엘리먼트를 제어하기 위해서는 그 엘리먼트를 조회하기 위한 식별자가 필요하다. 

HTML에서 엘리먼트의 이름과 id 그리고 class는 식별자로 사용된다. 식별자 API는 이 식별자를 가져오고 변경하는 역할을 한다.


(1) Element.tagName

해당 엘리먼트의 태그 이름을 알아낸다. 태그 이름을 변경하지는 못한다.

<ul>

    <li>html</li>

    <li>css</li>

    <li id="active" class="important current">JavaScript</li>

</ul>

<script>

console.log(document.getElementById('active').tagName)//읽기전용

</script>


(2) Element.id

문서에서 id는 단 하나만 등장할 수 있는 식별자다. 아래 예제는 id의 값을 읽고 변경하는 방법을 보여준다. 

<ul>

    <li>html</li>

    <li>css</li>

    <li id="active">JavaScript</li>

</ul>

<script>

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

console.log(active.id);

active.id = 'deactive';// id 값을 deactive로 변경

console.log(active.id);

</script>


(3) Element.className

클래스는 여러개의 엘리먼트를 그룹핑할 때 사용한다.

<ul>

    <li>html</li>

    <li>css</li>

    <li id="active">JavaScript</li>

</ul>

<script>

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

// class 값을 변경할 때는 프로퍼티의 이름으로 className을 사용한다.

active.className = "important current";

console.log(active.className);

// 클래스를 추가할 때는 아래와 같이 문자열의 더한다.

active.className += " readed"


(4) Element.classList

className에 비해서 훨씬 편리한 사용성을 제공한다.

<ul>

    <li>html</li>

    <li>css</li>

    <li id="active" class="important current">JavaScript</li>

</ul>

<script>

function loop(){

    //var active = document.getElementById('active');

    for(var i=0; i<active.classList.length; i++){

        console.log(i, active.classList[i]);

    }

}

// 클래스를 추가

</script>

<input type="button" value="DOMTokenList" onclick="console.log(active.classList);" />

<input type="button" value="조회" onclick="loop();" />

<input type="button" value="추가" onclick="active.classList.add('marked');" />

<input type="button" value="제거" onclick="active.classList.remove('important');" />

<input type="button" value="토글" onclick="active.classList.toggle('current');" />


DOMTokenList: class= a,b,c라면 각각의 a,b,c를 담아놓은 객체가 바로 DOMTokenList이다. -->유사배열



5. 조회 API

조회 API는 엘리먼트를 조회하는 기능이다. 조회 방법에 대해서는 이미 여러차례 살펴봤기 때문에 이번 시간에 알아볼 내용은 조회 대상을 제한하는 방법에 대한 것이다. 

지금까지 document.getElementsBy* 메소드를 통해서 엘리먼트를 조회했다. document 객체는 문서 전체를 의미하는 엘리먼트이기 때문에 document의 조회 메소드는 문서 전체를 대상으로 엘리먼트를 조회한다. Element 객체 역시도 getElementsBy* 엘리먼트를 가지고 있는데 Element 객체의 조회 메소드는 해당 엘리먼트의 하위 엘리먼트를 대상으로 조회를 수행한다. 

<ul>

    <li class="marked">html</li>

    <li>css</li>

    <li id="active">JavaScript

        <ul>

            <li>JavaScript Core</li>

            <li class="marked">DOM</li>

            <li class="marked">BOM</li>

        </ul>

    </li>

</ul>

<script>

    var list = document.getElementsByClassName('marked');

    console.group('document');

    for(var i=0; i<list.length; i++){

        console.log(list[i].textContent);

    }

    console.groupEnd();

     

    console.group('active');

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

    var list = active.getElementsByClassName('marked');

    for(var i=0; i<list.length; i++){

        console.log(list[i].textContent);

    }

    console.groupEnd();

</script>

실행결과)


6. 속성 API

속성은 HTML에서 태그명만으로는 부족한 부가적인 정보라고 할 수 있다. 이 속성을 어떻게 제어하는가 알아보자. 


속성을 제어하는 API는 아래와 같다. 각각의 기능은 이름을 통해서 충분히 유추할 수 있을 것이다.

- Element.getAttribute(name)

- Element.setAttribute(name, value)

- Element.hasAttribute(name);

- Element.removeAttribute(name);


<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 속성의 존재여부를 확인한다.--> true, false 리턴

</script>


(2) 속성과 프로퍼티

모든 엘리먼트의 (HTML)속성은 (JavaScript 객체의) 속성과 프로퍼티로 제어가 가능하다. 예제를 보자.

<p id="target">

    Hello world

</p>

<script>

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


    // attribute 방식

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

    // property 방식

    target.className = 'important';

</script>

setAttribute('class', 'important')와 className = 'important'는 같은 결과를 만든다. 하지만 전자는 attribute 방식(속성이라고 부르겠다)이고 후자는 property 방식이다.

property 방식은 좀 더 간편하고 속도도 빠르지만 실제 html 속성의 이름과 다른 이름을 갖는 경우가 있다. 그것은 자바스크립트의 이름 규칙 때문이다.

심지어 속성과 프로퍼티는 값이 다를수도 있다. 아래 코드를 실행한 결과는 속성과 프로퍼티의 값이 꼭 같은 것은 아니라는 것을 보여준다.

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

<script>

//현재 웹페이지가 http://localhost/webjs/Element/attribute_api/demo3.html 일 때 

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

// http://localhost/webjs/Element/attribute_api/demo1.html 

console.log('target.href', target.href);

// ./demo1.html 

console.log('target.getAttribute("href")', target.getAttribute("href"));

</script>


'WebFont-end > JavaScript' 카테고리의 다른 글

[JavaScript] Document 객체  (0) 2014.12.23
[JavaScript] Node 객체  (1) 2014.12.23
[JavaScript] HTMLCollection 객체  (0) 2014.12.22
[JavaScript] HTMLElement 객체  (0) 2014.12.22
[JavsScript] 제어 대상을 찾기  (0) 2014.12.21