[TIL Vanilla JS] 웹 제어하기

P1ush·2021년 9월 10일
0

TIL Vanilla JS

목록 보기
1/6

공부 날짜 : 2021.09.10 (금)

엘리먼트 찾기

  • document.getElementById(''); : ID 찾기
  • document.getElementsByTagName(''); : 태그로 찾기 (배열 리턴)
  • document.getElementsByClassName(''); : class로 찾기 (배열 리턴)


css 셀렉터 찾기

  • document.querySelector(''); : css 셀렉터로 찾기 (첫번째 요소만)
<ul class="navList">
     <li class="nav-item ft"></li>
     <li class="nav-item se"></li>
     <li class="nav-item th"></li>
</ul>

ul 안에 li.nav-item이라 할 때, querySelector는 첫번째 요소만 찾기 때문에 위에 있는 nav-item ft 가 선택이 됩니다.



  • document.querySelectorAll(''); : css 셀렉터로 찾기 (모든 요소,배열리턴)
<ul class="navList">
     <li class="nav-item ft"></li>
     <li class="nav-item se"></li>
     <li class="nav-item th"></li>
</ul>

뒤에 All이 붙으면 모든 요소를 찾기 때문에, 모든 nav-item이 선택됩니다.



속성값 수정 및 설정

  • element.style.property = ''; : 요소의 css 속성값 수정
    ex) document.getElementById('myh1').style.color = 'red';

  • element.setAttribute('',''); : 속성 정하기

<p><a id="abc" href="#">CODING FACTORY</a></p>

ex) document.getElementById( 'abc' ).setAttribute( 'href', 'https://www.codingfactory.net');

ID요소인 abc의 href 속성을 변경합니다.



부모,자식,형제 요소 선택

  • element.parentNode(''); : 부모 요소

    parentNode & parentElement?

    parentElement는 부모 노드가 없을 때 null 을 리턴하지만, parentNode는 Document node를 리턴합니다.
    https://dev-dain.tistory.com/128

  • element.nextElementSibling(''); : 현재요소의 다음 형제

  • element.previousElementSibling(''); : 현재요소의 이전 형제

  • element.children(''); : 자식 요소



innerText

<!DOCTYPE html>
<html lang="ko">
  <head>
    <meta charset="utf-8" />
  </head>
  <body>
    <h1>잔재미코딩 크롤링 테스트 페이지 (커리큘럼)</h1>

    <h3>나만의 엣지있는 블로그 사이트 만들기 (취미로 익히는 IT)</h3>
    <ul id="hobby_course_list">
      <li class="course" id="start">
        <a href="https://www.fun-coding.org">(왕초보) - 클래스 소개</a>
      </li>
      <li class="course" id="start">
        <a href="https://www.fun-coding.org"
          >(왕초보) - 블로그 개발 필요한 준비물 준비하기</a
        >
      </li>
      <li class="course" id="begin">
        <a href="https://www.fun-coding.org"
          >(왕초보) - Github pages 설정해서 블로그 첫 페이지 만들어보기</a
        >
      </li>
      <li class="course" id="begin">
        <a href="https://www.fun-coding.org"
          >(왕초보) - 초간단 페이지 만들어보기</a
        >
      </li>
      <li class="course" id="advanced">
        <a href="https://www.fun-coding.org"
          >(왕초보) - 이쁘게 테마 적용해보기</a
        >
      </li>
      <li class="course" id="advanced">
        <a href="https://www.fun-coding.org"
          >(왕초보) - 마크다운 기초 이해하고, 실제 나만의 블로그 페이지
          만들기</a
        >
      </li>
      <li class="course" id="advanced">
        <a href="https://www.fun-coding.org"
          >(왕초보) - 다양한 마크다운 기법 익혀보며, 나만의 블로그 페이지
          꾸며보기</a
        >
      </li>
    </ul>
    <script>
        const item = document.getElementById('start'); //start라는 이름의 ID요소찾기
        alert(item.innerText) //얼럿으로 텍스트출력
        //결과: (왕초보) - 클래스 소개  
        item.innerHTML = '<a href="https://www.fun-coding.org">(왕초보)</a>'
        //HTML요소 자체 변경

        const tags = document.getElementsByTagName('a'); //a인요소 모두 찾기
        alert(tags.length) //a태그인 요소의 개수를 찾아서 얼럿으로 출력
        // console.log(tags); 결과 : 7

        const items = document.querySelectorAll('#start');
        // css셀렉터가 #start인 요소 모두 찾기
        for (let i=0; i < items.length; i++){
            alert(items[i].innerText);
        }
        //items의 개수를 찾아서 텍스트로 출력
    </script>
  </body>
</html>



Append

<!DOCTYPE html>
<html>
  <head>
    <style>
      .box1 {
        width: 100px;
        height: 100px;
        border: 2px solid #f2b441;
        border-radius: 10px;
        text-align: center;
        line-height: 100px;
      }
    </style>
  </head>
  <body>
    <script>
        const newBox1 = document.createElement('div'); //div 생성
        newBox1.innerText = 'dave lee'; //div의 내용은 dave lee
        newBox1.setAttribute('class','box1'); //div의 class는 box1
        newBox1.style.background = '#f2d541'; //div의 배경색은 f2d541
       
        const newBox2 = document.createElement('div');
        newBox2.innerText = '20210910'
        newBox2.setAttribute('class','box2');
        newBox2.style.background = '#f2d541';   

        document.body.appendChild(newBox1); //body의 자식으로 생성
        document.body.removeChild(newBox1); //body 자식요소 제거
        document.body.appendChild(newBox2);
    </script>
  </body>
</html>



Attribute

<!DOCTYPE html>
<html>
  <head>
    <style>
      .box1 {
        width: 100px;
        height: 100px;
        border: 2px solid #f2b441;
        border-radius: 10px;
        text-align: center;
        line-height: 100px;
      }
    </style>
  </head>
  <body>
    <script>
        const newBox1 = document.createElement('div'); //div 생성
        newBox1.innerText = 'dave lee'; //div의 내용은 dave lee
        newBox1.setAttribute('class','box1'); //div의 class는 box1
        newBox1.style.background = '#f2d541'; //div의 배경색은 f2d541
        document.body.appendChild(newBox1); //body의 자식으로 생성
    </script>
  </body>
</html>



event

EventListener (mouseover & out)

<!DOCTYPE html>
<html>
  <head>
    <style>
      div {
        width: 100px;
        height: 100px;
        border: 2px solid #f2b441;
        border-radius: 10px;
      }
      .box1 {
        background: #f2d541;
      }
    </style>
  </head>
  <body>
    <div class="box1">ease</div>
    <script>
      const box = document.querySelector(".box1");
      //class box1 선택

      box.addEventListener("mouseover", () => {
        box.style.background = "red";
      });
      // 마우스오버 시 box 배경색을 레드로

      box.addEventListener("mouseout", () => {
        document.body.removeChild(box);
      });
      // 마우스가 영역 밖에 있으면 box가 사라짐.
    </script>
  </body>
</html>



addEventListener & removeEventListener

<!DOCTYPE html>
<html>
  <head>
    <style>
      div {
        width: 100px;
        height: 100px;
        border: 2px solid #f2b441;
        border-radius: 10px;
      }
      .box1 {
        background: #f2d541;
      }
    </style>
  </head>
  <body>
    <div class="box1">ease</div>

    <script>
      const makeRed = () => box.style.background = "red";
      const makeYellow = () => box.style.background = "#f2d541";

      const box = document.querySelector(".box1"); //클래스 box1 선택
      box.addEventListener("mouseover", makeRed); //마우스 오버시 
      box.addEventListener("mouseout", makeYellow); //마우스 영역밖일때
      box.addEventListener("click", () => { //클릭 시
        box.removeEventListener("mouseover", makeRed); //makeRed 이벤트삭제
        box.removeEventListener("mouseout", makeYellow); //makeYellow 이벤트삭제
      });

    </script>
  </body>
</html>

자료

0개의 댓글