seoyoung.dev

[javascript]-Element 객체( 식별자/조회/속성 ) 본문

WEB/Javascript

[javascript]-Element 객체( 식별자/조회/속성 )

seo-0 2019. 10. 22. 11:03
자바스크립트 시리즈는 '생활코딩-클라이언트 과목의 '웹브라우저 자바스크립트' 강의'를 참고로
공부하고 기록하기 위한 용도입니다. 

( DOM 은 HTML 만을 제어하기 위한 모델이 아니므로, Element 와 HTMLElement 라는 객체가 따로 구성된다. )

 

< Element 객체 >

*  식별자 API
    <ul>
        <li> html</li>
        <li>css</li>
        <li id="active" class="important current">JAVASCRIPT</li>
    </ul>

- Element.tagName

console.log(document.getElementById('active').tagName);

//tagName 은 변경 불가, Readonly

- Element.id

var Active = document.getElementById('active');
console.log(Active.id);   //active console창 출력 

Active.id = 'newId';  //active 가 id 인 HTMLLIElement객체의 id 를 변경
console.log(Active.id); //newId console 창 출력 

- Element.className

var Active = document.getElementById('active');
console.log(Active.className); //immportant current 출력 

Active.className = Active.className + 'addedclassName'; //+ 로 classname 추가 
console.log(Active.className);

- Element.classList

active.classList; //DOMTokenList 배열 형태로 클래스 이름 저장 

for(var i=0;i<active.classList.length;i++){
   console.log(active.classList[i]);
   }
* 조회 API

: 조회 API 는 엘리먼트를 조회하는 기능으로 document.getElementBy* 형태의 메소드를 사용하였다. 

이 중 조회 대상을 제한하는 경우를 보면, 

    <ul>
        <li class="marked"> html</li>
        <li>css</li>
        <li id="active">JAVASCRIPT
          <ul>
            <li class="marked">DOM</li>
            <li class="marked">BOM</li>
          </ul>
        </li>
    </ul>

( 그냥 document.getElementsByClassName('marked') 하면, 'html' 도, 'javascript'의 하위 태그들도 모두 조회된다. )

따라서, 

  <script>
        var lis=document.getElementById('active'); //유일한 id 의 객체를 얻어
        var list = lis.getElementsByClassName('marked'); //해당 id의 객체에서 className 으로 조회
        for(var i=0;i<list.length;i++){
          console.log(list[i].textContent);
        }
    </script>
* 속성 API
<a id="target" href="http://naver.com">naver</a>
<script>

    var t = document.getElementById('target');
   
    t.getAttribute('href');  //  http://naver.com
    
    t.setAttribute('title','NAVER'); //'title' 속성이 없으면 만들고, 있으면 'NAVER'로 변경 
    
    t.hasAttribute('title'); //'title' 이라는 속성을 갖고있으면 true 반환, 없으면 false 반환 
    
    t.removeAttribute('title'); //'title' 이라는 속성 삭제 
    
</script>

+ 속성과 프로퍼티 

<h1 id="target">hello </h1>
<script>

   var Target = document.getElementById('target');
    
    Target.setAttribute('class','important');   //attribute 방식 
    
    Target.className ='important'; //프로퍼티 방식 
    
</script>

( 프로퍼티 방식이 더 간단해보이지만, 속성과 상관없는 attribute 방식에 비해 프로퍼티 방식의 경우는 실제 속성과 다른 이름을 갖는 경우가 존재한다. ( class -> className , .. )

또한, 속성 방식과 프로퍼티 방식은 다른 값을 보여줄 수 있다. 

<a id="target" href="demo1.html">page </a>
<script>
 
 var t = document.getElementById('target');
 
 console.log(t.href);
 //프로퍼티 방식 -> file:///C:/Users/... 
 
 console.log(target.getAttribute('href');
 //속성 방식 -> demo1.html .. 
 
</script>