DOM 객체란?

박희수·2023년 11월 9일
0
post-thumbnail

🤗 자바스크립트의 DOM, 무엇일까?

"Document Object Model"

  • HTML 태그들을 하나씩 객체화한 것.
  • HTML 페이지의 내용과 모양을 제어하기 위해 사용되는 객체
  • HTML 태그당 DOM 객체가 하나씩 생성된다.
  • HTML 태그의 포함관계에 따라서 부모, 자식, 형제자매 관계로 구성된다.

클래스 이름을 이용해 DOM을 선택해보자 !

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>클래스 이름을 이용한 선택</title>
  </head>
  <body>
    <h1>클래스 이름을 이용한 선택</h1>
    <ul>
      <li class="odd">첫번째 아이템이에요!</li>
      <li class="even">두번째 아이템이에요!</li>
      <li class="odd">세번째 아이템이에요!</li>
      <li class="even">네번째 아이템이에요!</li>
      <li class="odd">다섯번째 아이템이에요!</li>
    </ul>
  </body>
  <script>
    console.log(document.getElementsByClassName("odd"));  
	➡️ 출력 결과 : HTMLCollection(3) getElementByClassName("클래스명") 이용
    ➡️ HTMLCollection(3) : > 배열이라는 뜻, 그리고 HTMLCollection은 프로토타입이다.
     0 : li.odd
     1 : li.odd
     2 : li.odd
     length : 3
     프로퍼티는 총 4개이다.

    HTMLCollection.prototype.forEach = Array.prototype.forEach;
    ⭐ 앞으로 HTMLCollection이라는 객체에는 prototype을 통해서 forEach라는 필드가 생기게 된다. 
       여기에 array가 만든 forEach를 넣어준다. 
       HTMLCollection에는 foreach라는 프로퍼티가 없었고, 
       array에는 있기 때문에 array가 만든 foreach를 넣어주면 밑의 예시가 정상적으로 실행된다.

    document.getElementsByClassName("odd").forEach(
      (v) => (v.style.color = "red")
      ➡️ v에는 각각의 객체가 순서대로 담긴다.
    );

    document
      .getElementsByClassName("even") ✅ even 클래스 선택 
      .forEach((v) => (v.style.color = "green")); ✅ 각 객체의 스타일 적용
	

    document.getElementsByTagName("h1").forEach((v) => (v.style.color = "red"));
	✅ v.style.color의 형태로 값의 스타일 변경 
  </script>
</html>

🤓 name 속성을 이용해 선택해 보자 !

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>name 속성을 이용한 선택</title>
  </head>
  <body>
    <h1>name 속성을 이용한 선택</h1>
    <form name="joinForm">
      <div>
        <input type="text" name="id" placeholder="아이디" value="phs8743" />
        <!-- 여기서 value는 사용자가 입력한 값을 가리킨다.-->
      </div>
      <div>
        <input type="password" name="pw" placeholder="비밀번호" value="1234" />
      </div>
      <div>
        <input type="checkbox" name="language" value="java" checked /> JAVA
        <input type="checkbox" name="language" value="C" /> C
        <input type="checkbox" name="language" value="python" /> python
      </div>
    </form>
  </body>
  <script>
    const pw = document.getElementByName("pw");
    // console.log(pw[0]);
    // 복수는 array 형태로 나와주기 때문에 [0], 이런 형태를 꼭 넣어줘야 한다.

    1. form 태그에 name 속성을 사용하면 따로 객체로 불러올 필요 없이 바로 사용 가능
    2. form 태그의 name이 이미 dom 객체의 이름이다. joinForm 은 dom객체의 이름
    3. 그래서 joinForm만 이용해서 객체를 불러올 수 있고,
    4. 폼태그의 프로퍼티는 name이 붙은 모든 것들이다.

    console.log(joinForm.pw); // name 옆에 붙은 이름 그대로 가져옴
    console.log(joinForm.id.value); // phs8743

    // joinForm에서 id를 name으로 가진 input 태그를 가져오고
    // 거기서 value 라는 프로퍼티를 가져온다.

    // if (!joinForm.id.value) {
    //   // joinForm.id.value = 값을 입력했다면 들어올 것이다.
    //   alert("아이디를 입력해 주세요"); // 안들어왔다는 가정하에
    // }

    // setAttribute("checked", "checked");
    // setAttribute에 checked라는 속성에 checked가 들어간다.
    // html이 써있는 checked는 프로퍼티가 아니고, 속성이다.
    // '.'을 이용해서 접근하는 다른 프로퍼티와는 다르다.

    // checked 프로퍼티로 수정
    const checkboxes = document.getElementsByName("language");
    checkboxes.forEach((checkbox) => {
      checkbox.checked = false; // 프로퍼티로 써주기
      console.log(checkbox.getAttribute("checked"));
      // check를 쓰면 빈문자열 반환
      // getAttribute는 html에 있는 속성값을 가져온다.
      console.log(checkbox.checked); // check를 쓰면 true 반환
      // 각각의 checkbox를 가져온다.
    });

    // HTML 태그에 checked 속성을 부여하면, js checked 프로퍼티를 false로 설정해도
    // checked 속성이 html 요소에 남아있다.
    // 따라서 체크 여부를 검사할 때에는 js 프로퍼티로 검사하는 것이 정확하다.
  </script>
</html>
profile
프론트엔드 개발자입니다 :)

0개의 댓글