JavaScript Attribute Node

Let's Just Go·2022년 6월 19일
0

JavaScript

목록 보기
5/10

JavaScript

Attribute Node

Attribute

  • Attribute
    • 태그의 id, value, class와 같은 것을 속성(Attribute)이라고 함

    • $찾은요소.attributes;

      • 태그 안의 속성을 얻을 수 있음

      • $찾은요소.attributes[].value 을 활용해서 찾은 요소의 안의 속성의 값들을 얻을 수 있음

      • $찾은요소.attributes.속성이름.value 을 활용해서 찾은 요소의 특정 속성안의 값을 얻거나 변경할 수 있음

    • Code

      <!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>Document</title>
      </head>
      
      <body>
          <input type="text" id="name" value="lee" class="user-name">
          <script>
              const $input = document.querySelector('input');
              // tag 선택자로 input 요소 가져옴
      
              console.log($input.attributes);
              console.log($input.attributes[1].value);
              // []을 통해서 값을 가져올 수 있음
              console.log($input.attributes.id.value);
              // 속성이름으로도 값을 가져올 수 있음
      
              $input.attributes.value.value = 'Moon';
              // 속성에 접근해서 값을 바꿔줄 수 있음
              $input.attributes.type.value = 'password';
          </script>
      
      </body>
      
      </html>

Set, Get

  • Set, Get
    • $찾은요소.getAttribute(’속성이름’);

      • 찾은요소의 속성 이름을 통해 값을 가져올 수 있음
    • $찾은요소.setAttribute(’속성이름', ‘변경할값');

      • 찾은요소의 속성 이름을 통해 값을 변경할 수 있고 추가할 수 있음
    • Code

      <!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>Document</title>
      </head>
      
      <body>
          <input type="text" id="name" value="lee" class="user-name">
          <p id='text'>Hello</p>
      
          <script>
              const $input = document.querySelector('input[type="text"]');
              // 다양한 방법으로 선택할 수 있음
      
              // input의 value 속성 값을 얻을 수 있음
              const $inputValue = $input.getAttribute('value');
              // input 태그의 value라는 이름의 값을 가져옴
      
              $input.setAttribute('value', '안녕하세요~');
              // input 태그의 value라는 이름의 값을 안녕하세요로 변경
      
              // p태그에 title 속성 추가
              const $paragraph = document.getElementById('text');
              $paragraph.setAttribute('title', '메롱');
      
              console.log($paragraph.hasAttribute('class'));
      
              if (!$input.hasAttribute('class')) {
                  // class가 없다면 생성 
                  $input.setAttribute('class', '클래스~');
              } else {
                  $input.removeAttribute('class');
              }
              $paragraph.removeAttribute('class');
          </script>
      
      </body>
      </html>

Dataset

  • Dataset
    • $찾은요소.dataset.키워드

      • data- 로 시작하는 속성을 가져올 수 있고 속성을 추가할 수 있음

      • 키워드에 data- 뒤에 작성된 내용을 넣으면 쉽게 불러올 수 있음

    • Code

      <!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>Document</title>
      </head>
      
      <body>
          <ul id="users">
              <li data-user-id="Moon123" data-role="common" id="1">Moon</li>
              <li data-user-id="Lee456" data-role="admin" id="2">Lee</li>
          </ul>
      
          <script>
              const $users = document.getElementById('users');
              // ul 태그값 가져옴
      
              // 배열 디스트럭처링
              const [$user1, $user2] = [...$users.children];
      
              /*
              data- 로 시작하는 어트리뷰트와 dataset 프로퍼티를 사용하면 HTML요소와 자바스크립트 간에 데이터를 쉽게 교환할 수 있음
              data- 뒤에는 원하시는 특정 키워드를 작성하고 dataset 프로퍼티를 이용하여 data+키워드 로 값을 가지고 오면 됨
              */
              console.log($user1.getAttribute('data-role'));
              console.log($user1.dataset);
              // dataset은 data- 키워드를 가져올 수 있음
              console.log($user1.dataset.role);
              // JS는 케밥케이스(-)로 되어 있는 data-속성을 카멜케이스로 변환해서 가져올 수 있음
              console.log($user1.dataset.userId);
              // dataset이라는 프로퍼티를 통해서 data
      
              $user2.dataset.role = 'anonymous';
              $user2.dataset.userTelNumber = '010-1234-5678';
              // 속성을 추가 및 값 변경 가능
      
              // body 태그를 얻는 법 
              const $body = document.body;
      
              
              // html 태그를 얻는 법 
              const $html = document.documentElement;
          </script>
      </body>
      
      </html>

Class Manipulation

  • Class_Manipulation

    • $찾은요소.classList.조작함수

      • 조작 함수를 통해 클래스 조작 연산 수행 가능

      • add, replace, remove, contains

      • 위의 명령어들을 사용해서 클래스를 추가, 대체, 삭제 등의 연산 수행 가능

      • toggle() : 해당 클래스가 존재하면 삭제, 존재하지 않으면 추가

    • Code

      <!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>Document</title>
      
          <style>
              .box {
                  width: 100px;
                  height: 100px;
                  background: lightgray;
                  margin: 0 auto;
                  text-align: center;
                  line-height: 100px;
              }
      
              .red {
                  color: skyblue;
              }
      
              .green {
                  color: green;
              }
      
              .circle {
                  border-radius: 50px;
                  /* 모서리 둥글 둥글하게 */
              }
          </style>
      </head>
      <body>
          <div class="box red">Hello</div>
      
          <script>
              const $box = document.querySelector('.box');
              console.log($box.attributes.class.value);
              console.log($box.getAttribute('class'));
              console.log($box.className);
              // 지정한 요소의 클래스 이름을 불러오는 것
      
              // $box.setAttribute('class', 'blue');
              // 이렇게 하면 class이름에 blue가 들어감
      
              // $box.setAttribute('class', 'box blue');
              // $box.className = 'box blue';
              // 클래스 조작은 classList 프로퍼티 사용 
              console.log($box.classList);
      
              $box.classList.add('circle');
              // class 이름을 넣어주면 class 추가 가능
              $box.classList.add('abc', 'def', 'ghi');
      
              // 요소에 특정 클래스 교체
              $box.classList.replace('red', 'green');
      
              // 요소에 특정 클래스를 삭제 
              $box.classList.remove('circle');
              $box.classList.remove('abc', 'def', 'ghi');
      
              // 요소에 특정 클래스가 존재하는지 확인 
              console.log($box.classList.contains('red'));
      
              // toggle() : 해당 클래스가 존재하면 삭제, 존재하지 않으면 추가
              $box.classList.toggle('circle');
          </script>
      </body>
      
      </html>
profile
안녕하세요! 공부한 내용을 기록하는 공간입니다.

0개의 댓글