ABOUT ME

Today
Yesterday
Total
  • 속성(Attribute)와 프러퍼티(Property)
    JavaScript/DOM 2022. 11. 21. 18:57

    - 속성 — HTML 안에 쓰임
    - 프로퍼티 — DOM 객체 안에 쓰임 

     

     

    - 브라우저(browser)는 웹페이지를 만나면 HTML을 읽어(파싱(parsing)) DOM 객체를 생성한다

    (즉, 브라우저(browser)가 HTML문서를 해석할 때 DOM객체가 만들어진다) 

    - HTML태그들이 가지고 있는 속성들은 요소노드의 프로퍼티(property)가 된다 

    - 하지만 모든 속성들의 요소들의 프로퍼티(property)가 되지는 않는다 

     

     

    <!DOCTYPE html>
    <html lang="ko">
    <head>
      <meta charset="UTF-8">
      <title>JS with Codeit</title>
    </head>
    <body>
      <div>
        <h1>오늘 할 일</h1>
    		<ol id="today">
          <li class="item">자바스크립트 공부</li>
    			<li class="item">고양이 화장실 청소</li>
    			<li class="item">고양이 장난감 쇼핑</li>
    		</ol>
    		<h1>내일 할 일</h1>
        <ol id="tomorrow" href="https://www.codeit.kr">
          <li class="item"><a href="https://developer.mozilla.org/ko/docs/Web/JavaScript">자바스크립트 공부</a></li>
    			<li class="item">뮤지컬 공연 예매</li>
    			<li class="item">유튜브 시청</li>
    		</ol>
      </div>
      <script src="index.js"></script>
    </body>
    </html>
    // HTML 속성 (HTML attribute)
    const tomorrow = document.querySelector('#tomorrow');
    const item = tomorrow.firstElementChild;
    const link = item.firstElementChild;
    
    
    
    
    // id속성 
    console.log(tomorrow); // <ol id="tomorrow" href="https://www.codeit.kr">... </ol>  
    console.log(tomorrow.id); // tomorrow
    
    
    
    // class 속성 
    console.log(item);  //  <li class="item"><a href="https://developer.mozilla.org/ko/docs/Web/JavaScript">자바스크립트 공부</a.....</li>
    console.log(item.className);  // item
    
    
    // href속성 
    console.log(link); // <a href="https://developer.mozilla.org/ko/docs/Web/JavaScript">자바스크립트 공부</a>
    console.log(link.href);  // https://developer.mozilla.org/ko/docs/Web/JavaScript
    
    
    console.log(tomorrow.href);  // undefined !! 왜냐하면은?! ==> ol태그와 href속성은 표준속성이 아니기 때문이다

     

    HTML태그가 표준 속성이 아닌(비표준 속성) 경우에는 어떻게 접근할까?!

    - 아래의 메서드를 사용하면은 표준, 비표준 관계없이 접근할 수 있다 속성과 함께 쓰이는 메서드

    -  name, 즉 속성 이름들은 대소문자를 구분하지 않는다.

    - elem.hasAttribute(name) — 속성 존재 여부 확인
    - elem.getAttribute(name) — 속성값을 가져옴
    - elem.setAttribute(name, value) — 속성값을 변경함
    - elem.removeAttribute(name) — 속성값을 제거함
    - elem.attributes 은 속성의 모음(collection)을 반환함

     

    console.log(tomorrow.getAttribute('href'));  // 비표준속성(ol태그 href속성)  https://www.codeit.kr
    console.log(link.getAttribute('href'));  // 표준(a태그 href속성) https://developer.mozilla.org/ko/docs/Web/JavaScript
    console.log(item.getAttribute('class'));

     

     

    tomorrow.setAttribute('class', 'days_list'); // class="days_list" 를 추가 해준다
    link.setAttribute('href', 'https://www.google.com')  // https://developer.mozilla.org/ko/docs/Web/JavaScript => https://www.google.com로 변

     

    tomorrow.removeAttribute('href'); 
    tomorrow.removeAttribute('class');

    댓글

Designed by Tistory.