33일차 2023-04-21

2023. 4. 21. 19:02JavaScript

Html5

 

removeChild는 자식만 지움 
span.removeChild(span.fistChild.firstChild);//이렇게는 안됨. 왜냐하면, 자식이 아닌 손자 삭제니깐.
(하나 아래만 삭제 가능)
그럼 들어가는 것을 한 칸 아래로 들어가서 삭제하면 됨
span.span.remove();이런 식으로

자바스크립트에서 table 만드는 방법 숙지

 

Span15.html

<!DOCTYPE html>
<html lang="ko">
  <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>Span15.html</title>
    <style>
      .monday {
        font-size: 0.8em;
        color: gray;
      }
      .html5 {
        font-size: 1.8em;
        color: rgb(45, 148, 60);
        font-weight: bold;
      }
    </style>
    <script>
      var toggle = false;
      function toggleText() {
        var span = document.getElementById("text");
        if (!toggle) span.innerHTML = "자바스크립트";
        else span.textContent = "JavaScript";
        toggle = !toggle;
      } ////////////
      var setImage = function () {
        var span = document.getElementById("image");/*image id를 가진 요소를 선택하여 요소의 속성을 변경하거나 이벤트 추가하는 작업수행*/
        //방법1
        //span.innerHTML="<img src='../Images/button.jpg' alt='이미지'/>";
        //방법2
        var imgNode = document.createElement("img");/*img태그 요소를 만듭니다.그리고 imgNode변수에 할당*/
        //imgNode.setAttribute('src','../Images/button.jpg');/*imgNode요소의 src 속성을 설정하여 이미지 파일 경로 지정*/
        //imgNode.setAttribute('alt','이미지');/*imgNode요소의 alt 속성을 설정하여 이미지에 대한 대체 텍스트를 '이미지'로 지정*/
        imgNode.src = "../Images/button.jpg";/*imgNode객체를 생성했기 때문에 . 으로 속성을 불러올 수가 있다.*/
        imgNode.alt = "이미지";
        //span.textContent="";/*텍스트를 빈문자로 바꿔버림,하지만 span에 복잡하게 있으면 그 안에 싹다 지우는거라 비추천*/
        span.removeChild(span.firstChild);
        span.appendChild(imgNode);
      };

      function printGugudan() {
        var span = document.getElementById("gugudan");/*id가 gugudan인 요소를 찾아서 span에 넣음*/
        var table =
          "<table style='width:700px;text-align:center;background-color:red;border-spacing:1px'>";/*테이블을 만들기 위한 html코드를 문자열 형태로 변수 table에 할당*/
        for (var i = 1; i <= 9; i++) {
          table += "<tr style='background-color:white'>";/*table변수에 <tr>태그를 추가. 행을 만듬*/
          for (var k = 2; k <= 9; k++) {
            table += "<td>" + k + "*" + i + "=" + i * k + "</td>";/*table변수에 <td>태그를 추가. 테이블 샐을 만듬. 셀 안에는 구구단의 결과가 들어감 */
          }
          table += "</tr>";/*table변수에 </tr>을 추가하여 행을 닫음*/
        }
        table += "</table>";/*table변수에 /</table>를 추가하여 테이블을 닫음*/
        span.innerHTML = table;/*요소의 내용을 table변수의 내용으로 변경. html문서 내에 id가 gugudan인 요소에 구구단 테이블 표시*/
      } ///////////
    </script>
  </head>
  <body>
    <!--
           일반적인 HTML태그와 달리 MARKUP기능은 없다.
           주로 자바스크립트와 CSS에서 활용(제어)하기 위한 태그
    -->
    기본 텍스트
    <h2>&lt;span&gt;태그</h2>
    <span>기본 텍스트</span>
    <h3>자바스크립트에서 활용</h3>
    오늘의 첫 수업은 <span id="text">JavaScript</span>입니다<br />
    여기에 <span id="image">이미지</span> 표시하기<br />
    아래에 구구단 표시하기<br />
    <span id="gugudan"><!--여기에 생성됨--></span>
    <fieldset>
      <legend>버튼들</legend>
      <button onclick="toggleText()">텍스트 변경</button>
      <button onclick="setImage()">이미지 교체</button>
      <button onclick="printGugudan()">구구단 표시</button>
    </fieldset>
    <h3>CSS에서 활용</h3>
    오늘은 <span class="monday">월요일</span> 입니다<br />
    <span class="html5">HTML5</span> 수업입니다
  </body>
</html>

결과)

 

 

Fieldset16.html

<!DOCTYPE html>
<html lang="ko">
  <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>Fieldset16.html</title>
  </head>
  <body>
    <!--
       fieldset태그: 어떤 영역을 범주화할때 사용하는
                     태그
                     또한 하위태그로 legend태그를
                     사용해서
                     머릿말을 표시할 수 있다.

                     -block element

        address태그:주소를 표시할때 사용하는 태그
                     글자가 기울어진 형태로 보임.
                    -block element
    -->
    <div>
      <h2>&lt;fieldset&gt;태그</h2>
      <fieldset>
        <legend>당신이 좋아하는 스포츠는?</legend>
        <ul style="list-style-type: decimal">
          <li>축구</li>
          <li>배구</li>
          <li>야구</li>
          <li>농구</li>
        </ul>
      </fieldset>
      <h2>&lt;address&gt;</h2>
      <address style="font-style: normal; text-align: center">
        서울시 금천구 가산동 한국 소프트웨어 인재개발원
      </address>
    </div>
  </body>
</html>

결과)

Fieldset16.html

<fieldset>태그

당신이 좋아하는 스포츠는?
  • 축구
  • 배구
  • 야구
  • 농구

<address>

서울시 금천구 가산동 한국 소프트웨어 인재개발원

 

css3

 

//모든 태그 선택
*{

}
태그명으로 시작
span{

}
클래스명 선택은.으로
.positive{

}
아이디 선택은 #으로
#bas{

}
/*li태그 중에서 myclass라는 클래스명을 가진 li태그*/
li.myclass{

}
/*li의 하위 태그 중에서 myclass라는 클래스명을 가진 태그*/
li .myclass{//스페이스 하나이상 줌

}

Selector01_1.html

<!DOCTYPE html>
<html lang="ko">
  <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>Selector01_1.html</title>
    <style>
      /* CSS코드는 style 태그 안에서 작성 */
      /* 전체 선택자 : *로 모든 태그(body이하부터)선택
            -글꼴이나 혹은 여백을 처음에 전체에 적용할때 사용*/
      * {
        margin: 0;
        font-family: Verdana, Geneva, Tahoma, sans-serif;
      }
      /* 태그 선택자 : 태그명으로 선택*/
      span {
        color: green;
        font-size: 1.8em;
      }
      /* 클래스 선택자: .클래스명 으로 선택-한 페이지안에 클래스명 중복가능*/
      .positive {
        font-weight: bold;
        background-color: yellow;
      }
      .negative {
        color: gray;
        font-size: 0.8em;
      }
      /* 하위 선택자: 스페이스로 구분하여 선택*/
      .mydiv span {
        color: red;
        font-size: 0.8em;
      }
      /* 자식 선택자: > 로 구분해서 선택*/
      .mydiv > span {
        color: cyan;
        font-size: 1.2em;
      }
      /* 다중 선택자:,(콤마)로 구분해서 여러 선택자 사용*/
      .multi h2,
      .multi h3,
      h4,
      h5 {
        color: blue;
      }
      /* 아이디 선택자:#아이디명 으로 선택-아이디는 한 페이지 안에서 중복 불가*/
      #bas {
        color: yellow;
      }
      /* li태그중에서 myclass 라는 클래스명을 가진 li태그*/
      li.myclass {
        color: yellow;
      }
      /* li의 하위 태그중에서 myclass라는 클래스명을 가진 태그*/
      li .myclass {
        color: red;
      }
    </style>
  </head>
  <body>
    <h2>태그 선택자/클래스 선택자</h2>
    <div>
      저의 <span class="positive">장점</span>은
      <span class="positive">긍정적인 성격</span> 입니다.<br />
      저의 <span class="negative">단점</span>은
      <span class="negative">지저분한 스타일</span> 입니다.
    </div>
    <h2>하위 및 자식 선택자</h2>
    <div class="mydiv">
      <span>DIV안의 SPAN태그</span>
      <fieldset>
        <span>FIELDSET안의 SPAN태그</span>
      </fieldset>
    </div>
    <h2>다중 선택자</h2>
    <div class="multi">
      <h2>제목2</h2>
      <h3>제목3</h3>
      <h4>제목4</h4>
      <h5>제목5</h5>
    </div>
    <h2>아이디 선택자</h2>
    <ul>
      <li class="myclass"><b class="myclass">축구</b></li>
      <li id="bas">농구</li>
      <li class="myclass">배구</li>
    </ul>
    <h3>h3태그입니다</h3>
  </body>
</html>

결과)

 

 

input태그에서 속성type="text or type=text 에서 '이나 "으로 감싸거나 감싸지 않아도 되는데 특수문자이면 감싸야 된다. (type="*")
/*주소중 na가 포함된거 선택*/

Selector01_2.html

<!DOCTYPE html>
<html lang="ko">
  <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>Selector01_2.html</title>
    <style>
      h1 {
        color: green;
      }
      input {
        color: green; /* 입력	글자 스타일 변경*/
        font-size: 1.4em;
        font-weight: bold;
      }
      /* 속성 선택자 :선택자[속성]*/
      h1[title] {
        /*title속성이 있는 h1태그 선택*/
        border: 1px red solid;
      }
      /* 속성값은 "이나 '으로 감싸거나 특수 문자가
            포함되지 않은 경우는 감싸지 않아도 된다.*/
      input[type="text"] {
        color: #ff0000;
      }
      /*input태그중 type속성이 checkbox 인 요소중 체크된 요소 선택*/
      input[type="checkbox"]:checked {
        width: 30px;
        height: 30px;
      }
      /* 속성에 정규 표현식 적용*/

      a[href*="na"] {
        /* *는 포함됨의 의미  */
        color: #ffb300;
        font-size: 1.4em;
      }
      a[href$="net"] {
        /*  $는 끝나는 의미*/
        color: #cc00ff;
      }
      a[href^="http"] {
        /*  ^는 시작의 의미 */
        border: 5px dotted blue;
      }
      h3 ~ div {
        /* h3 동생들인 div*/
        color: aqua;
      }
      h3 + div {
        /*바로 밑에 동생*/
        color: red;
      }
    </style>
  </head>
  <body>
    <h1>title속성이 없는 h1태그</h1>
    <h1 title="제목 태그입니다">title속성이 있는 h1태그</h1>
    <form>
      이름:<input type="text" /><br />
      아이디:<input type="text" /><br />
      비밀번호:<input type="password" /><br />
      전화번호:<input type="tel" /><br />
      남자:<input type="checkbox" checked /><br />
      여자:<input type="checkbox" />
    </form>
    <h2>정규 표현식 사용</h2>
    <a href="http://www.naver.com">네이버</a><br />
    <a href="http://www.daum.net">다음</a><br />
    <a href="www.nate.com">네이트</a>
    <div>div0</div>
    <h3 id="title">동위(+,~) 선택자</h3>
    <div>div1</div>
    <div>div2</div>
    <fieldset>
      <div>div3</div>
    </fieldset>
    <div>div4</div>
    <div>div5</div>
  </body>
</html>

결과)

 

:(콜론은 ~중에라고 해석하면된다)

Selector01_3.html

<!DOCTYPE html>
<html lang="ko">
  <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>Selector01_3.html</title>
    <style>
      #content {
        background-color: yellow;
        width: 300px;
      }
      ul li {
        list-style: none;
        border: 1px green solid;
        font-size: 1.4em;
        font-weight: bold;
        height: 50px;
      }
      /*
        선택자 : (콜론 하나)의 의미는 "선택자중에" 라는 의미
        선택자 :: (콜론 두개)의 의미는 "선택자의 컨텐츠중에"의 의미
        */

      /* nth-child(숫자) : 숫자는 1부터 시작하고  특정 자식을 선택할때*/
      div#content li:nth-child(2) {
        color: red;
      }
      /*홀수번째 만 선택:n은 0부터 시작 1씩 증가*/
      div#content li:nth-child(2n + 1) {
        color: rgb(114, 13, 184);
      }
      /*짝수번째 만 선택:n은 0부터 시작 1씩 증가*/
      div#content li:nth-child(2n) {
        color: rgb(3, 148, 128);
      }
      ul li:last-child {
        background-color: aqua;
      }
      div#content li:first-child {
        border-radius: 10px 10px 0 0;
        background-color: red;
      }
      div#content li:last-child {
        border-radius: 0 0 10px 10px;
        background-color: red;
      }

      #start::first-letter,
      #end::first-letter {
        font-size: 2em;
      }
      #start::first-line,
      #end::first-line {
        color: red;
        font-weight: bold;
      }
      /*첫번째 P태그의 컨텐츠 중에서 마우스로 드래그한 컨텐츠*/
      #character p:first-child::selection {
        color: yellow;
        background-color: black;
      }
    </style>
  </head>
  <body>
    <h1>구조 선택자</h1>
    <div id="content">
      <ul>
        <li>menu1</li>
        <li>menu2</li>
        <li>menu3</li>
        <li>menu4</li>
        <li>menu5</li>
        <li>menu6</li>
      </ul>
    </div>
    <h1>문자 선택자</h1>
    <div id="character">
      <p id="start">
        2020년 1월 6일<br />
        6기 시작
      </p>
      <p id="end">
        2020년 7월 24일<br />
        6기 종료
      </p>
    </div>
    <div>
      <ul>
        <li>menu1</li>
        <li>menu2</li>
        <li>menu3</li>
        <li>menu4</li>
        <li>menu5</li>
        <li>menu6</li>
      </ul>
    </div>
  </body>
</html>

결과) 드래그 시 배경색깔 글색깔 변경됨

 

Selector01_4.html

<!DOCTYPE html>
<html lang="ko">
  <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>Selector01_4.html</title>
    <style>
      ul > li {
        color: green;
        font-size: 2em;
        font-weight: bold;
        border: 1px red solid;
      }
      /*반응 선택자 - 사용자의 반응에 따라 요소(태그)를 선택*/
      li:hover {
        /*마우스가 올라간 li태그*/
        color: red;
      }
      li:active {
        /* 마우스로 해당 태그 영역을 클릭한 요소를 선택*/
        color: yellow;
        background-color: black;
      }
      /* 상태 선택자:요소의 상태에 따라 선택*/
      input:focus {
        /* input태그중 focus상태에 있는 input태그*/
        background-color: yellow;
        border: 2px dotted red;
      }
      input:enabled {
        /* input태그중 활성화 상태인 input태그*/
        color: red;
        font-weight: bold;
      }
      input:disabled {
        /* input태그중 비활성화 상태인 input태그*/
        color: rgb(25, 25, 31);
        background-color: aqua;
        border: 5px dashed pink;
      }
    </style>
  </head>
  <body>
    <h1>반응 선택자</h1>
    <div>
      <ul>
        <li>menu1</li>
        <li>menu2</li>
        <li>menu3</li>
        <li>menu4</li>
        <li>menu5</li>
        <li>menu6</li>
      </ul>
    </div>
    <h1>상태 선택자</h1>
    <div>
      <form>
        이름 : <input type="text" name="name" value="기본 텍스트" /><br />
        아이디 : <input type="text" name="id" /><br />
        비번 : <input type="password" name="pwd" value="1234" disabled />
      </form>
    </div>
  </body>
</html>

결과)

 

Selector01_5.html

<!DOCTYPE html>
<html lang="ko">
  <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>Selector01_5.html</title>
    <style>
      a {
        color: black;
        text-decoration: none;
      }
      /* 링크 선택자:링크가 걸린 컨텐츠의 사용자 반응에 따라 요소 선택*/
      a:hover {
        /*마우스 오버시*/
        color: green;
        text-decoration: underline;
      }
      a:active {
        /*마우스 클릭시*/
        color: red;
      }
      a:visited {
        /* 방문했던 주소*/
        color: aqua;
      }

      /* after선택자:선택 된 태그가 감싸고 있는 컨텐츠의 뒤에 다른 내용을 추가하고자 할때*/
      ul.link a::after {
        content: "-" attr(href);
      }
      /* 부정 선택자: not(제외할 선택자) 함수 사용:선택된 요소중 특정 요소 제외시*/
      ul.not li:not(.odd) {
        background-color: yellow;
      }
    </style>
  </head>
  <body>
    <h1>링크 선택자</h1>
    <div>
      <ul class="link">
        <li><a href="http://www.nate.com">네이트</a></li>
        <li><a href="http://www.naver.com">네이버</a></li>
        <li><a href="http://www.daum.net">다음</a></li>
        <li><a href="http://www.google.com">구글</a></li>
        <li><a href="SELECTOR01_1.html">페이지</a></li>
        <li><a href="http://www.baewoomart.co.kr">배움센터</a></li>
      </ul>
    </div>
    <h1>부정 선택자</h1>
    <div>
      <ul class="not">
        <li class="odd"><a href="http://www.naver.com">네이버</a></li>
        <li><a href="http://www.nate.com">네이트</a></li>
        <li class="odd"><a href="http://www.daum.net">다음</a></li>
        <li><a href="http://www.google.co.kr">구글</a></li>
      </ul>
    </div>
  </body>
</html>

결과) 한번 들어간 링크는 cyan색으로 변경됨

클래스 2개보다 클래스 3개 적용이 가깝게 적용(클래스 많은 게 적용됨)
.box-1.box-2.box-3{}   >     .box-2.box-3{}

OrderOfSelector02.html

<!DOCTYPE html>
<html lang="ko">
  <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>OrderOfSelector02.html</title>
    <!--embedding style :style태그로 css설정-->
    <link href="styles/style.css" rel="stylesheet" />
    <style>
      /*
            [선택자 사이의 우선순위]
            !important > inline style > id선택자 > class선택자 > 태그선택자> *
            ※우선 순위가 같다면 태그랑 가까운 css가 적용된다(인터프리터 방식 이니까)
        */
      h1 {
        color: blue;
      }
      h1 {
        color: red;
      }
      #sea {
        color: blue;
      }
      .sea {
        color: red;
      }
      .mountain {
        color: green;
      }
      li {
        color: yellow !important;
      }
      dd {
        color: blue;
      }
    </style>
  </head>
  <body>
    <h1>선택자 종류에 따른 CSS적용순서</h1>
    <ul>
      <li class="mountain">관악산</li>
      <li class="mountain">치악산</li>
      <!-- inline style(태그안에 style 속성으로 css설정)-->
      <li class="sea" id="sea" style="color: pink">경포대</li>
      <li class="sea">해운대</li>
    </ul>
    <h1>
      CSS적용 스타일(inline style,embedding style,external style)에 따른 적용
      순서
    </h1>
    <dl>
      <dd class="local">종로구</dd>
      <dd>강서구</dd>
      <!-- inline style(태그안에 style 속성으로 CSS설정)-->
      <dd style="color: red">강동구</dd>
      <dd>강남구</dd>
    </dl>
    <h2>여러 클래스명을 동시에 사용하기</h2>
    <style>
      .box-2 {
        width: 200px;
        height: 50px;
        background-color: green;
        border-radius: 10% 5%;
      }
      .box-3 {
        background-color: aqua;
      }
      .box-1 {
        width: 100px;
        height: 100px;
        background-color: red;
      }
      .box-1.box-2.box-3 {
        background-color: yellow;
      }
      .box-2.box-3 {
        background-color: pink;
      }
    </style>
    <div class="box-1 box-2 box-3">BOX1</div>
    <div class="box-2 box-3">BOX2</div>
    <h2>최종 선택자가 우선순위가 같은 경우</h2>
    <style>
      /*최종 선택자의 수선 순위가 같은 경우
        오른쪽에서 왼쪽으로 이동하면서 css의 우선순위가 적용된다*/
      .depth1 #depth2 #depth3 input {
        background-color: red;
      }
      #depth1 #depth2 #depth3 input {
        background-color: green;
      }
    </style>
    <div class="depth1" id="depth1">
      <div class="depth2" id="depth2">
        <div class="depth3" id="depth3">
          <input type="text" />
        </div>
      </div>
    </div>
  </body>
</html>

결과) dl의 하위 dd를 노란색으로 처음에 외부로 link로 설정했으나 i 

 

 

JavaScript

 

 

window.addEventListener("DOMContentLoaded", function () {});
윈도우객체에(window).
이벤트 리스너를 붙인다(addEventListener)=>리스너가 이벤트가 발생하는지 발생하지 않는지 감지하는 애
(DOMContentLoaded)=> Dom(html body에 있는 게 메모리에 올라가면, 화면에 다 보여주면)
그다음에 function(){}을 실행
그래서 윈도우 객체에 이벤트가 발생하는지 발생하지 않는지 체크하고 메모리 올리면 함수 실행

getElements ~~
여기서 s는 유사배열을 뜻함
document.querySelect

append()에는 문자열과 노드를 넣을 수 있음
appendchild()에는 노드만 넣을 수 있음

DOM09_1.html

<!DOCTYPE html>
<html lang="ko">
  <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>DOM09_1.html</title>
    <style>
      .box {
        background-color: yellow;
      }
    </style>
    <script>
      /*
    BOM(Browser Object Model) : 브라우저를 스크립트 언어로 제어하기 위해 객체로 모델링 한 것.
                                그래서 자바스크립트에서 BOM API를 사용해서 브라우저를 제어 할 수 있다
                                window객체(브라우저와 같다)는 BOM의 최상위 객체이다.즉 전역객체로 브라우저당 1개이다
                                 
    DOM(Document Object Model) : HTML문서를 스크립트 언어로 제어하기위해 객체로 모델링 한 것
                                 그래서 자바스크립트에서 DOM API를 사용해서 HTML문서를 제어 할 수 있다
                                 DOM의 최상위 노드는 window객체의 자식인 document객체이다
                                 document객체는 HTML문서 하나당 하나다

    아래는 HTML문서와 관련된 DOM API이다
    1.노드 생성
      document객체의 createElement("태그명") 혹은 createTextNode("텍스트")
      

      
    2.생성된 노드 부모에 붙이기
      부모요소.prepend(노드 혹은 문자열(텍스트노드)) :부무의 자식요소 맨 앞에 붙인다
      부모요소.append(노드 혹은 문자열(텍스트노드)) :부모의 자식요소 맨 뒤에 붙인다
      부모요소.appendChild(노드)

      부모요소.insertBefore(삽입할노드, 기존 자식노드);삽입할 노드가 기존 자신 노드 이전 위치에 삽입된다      
      기존요소.insertAdjacentElement(위치,새노드);부모요소가 필요없다 즉 기존요소를 기준으로 위치를 정해서 삽입한다
      기존요소.insertAdjacentHTML(위치,'태그형태의 문자열')
      
      ※insertBefor 와 insertAdjacentElement차이점
      insertBefore() requires you to provide the parent node, an existing child node, and the new node to be inserted; the new node is put before the child node
      insertAdjacentElement only requires you to provide an existing node and the new node. The new node is inserted at some place related to the existing node. 
	  There's no need to provide the parent node.
    
    3.노드 추가 및 삭제
      -부모의 자식요소 끝에 추가
      부모요소.append(자식요소 혹은 문자열);
      부모요소.appendChild(자식요소);
      -부모의 자식요소 앞에 추가
      부모요소.prepend(자식요소 혹은 문자열);
      부모요소.removeChild(자식요소)
      자신요소.remove()

      append()와 appendChild()의 차이점:
      Element.append() allows you to also append string objects, whereas Node.appendChild() only accepts Node objects.
      Element.append() has no return value, whereas Node.appendChild() returns the appended Node object.
      Element.append() can append several nodes and strings, whereas Node.appendChild() can only append one node.

    4.노드 복제
      타켓요소.cloneNode(true)

    5.노드 가져오기:

      태그명으로 얻어 오기
      document.getElementsTagName("태그명");
      name속성으로 얻어 오기
      document.getElementsByName("name속성 값");
      클래스명으로 얻어오기
      document.getElementsByClassName("클래스명")
      id값으로 얻어 오기
      document.getElementById("id속성값");
      document.querySelector('css선택자') 
      일치하는 요소가 있으면 무조건 첫번째 요소만 반환.없으면 null반환
      document.querySelectorAll('css선택자')
      일치하는 모든 요소반환(Nodelist) 없으면 length가 0인 Nodelist반환

      속성
      childNodes속성는 텍스트나 주석등도 노드로 처리
      children속성은 엘리먼트 노드(태그)만 노드로 처리

      아래는 엘리먼트 노드뿐만 아니라 텍스트 노드(주석포함)도 대상이된다
      parentNode   
      firstChild  는 children[0]과 같다
      lastChild
      previousSibling  
      nextSibling
      엘리먼트 노드(태그) 대상일때는
      parentElement
      firstElementChild  는 children[0]과 같다
      lastElementChild
      previousElementSibling
      nextElementSibling 
    
    6.노드 대체하기
      타켓요소.replaceWith(새노드);
    */
      window.addEventListener("DOMContentLoaded", function () {
        var fieldset = document.querySelector("fieldset");
        var span = document.querySelector("div.box > span");
        var divNode = document.querySelector(".box");
        console.log(divNode);
        //childNodes속성는 NodeList타입(모든 노드(주석및 텍스트포함)를 담은 컬렉션(유사배열))
        console.log(divNode.childNodes); //NodeList(4) [text, comment, span, text]
        console.log(divNode.childNodes[0]); //▶#text 클릭시(data: "\n    ")
        console.log(divNode.childNodes[0].nodeName); //#text(노드명)
        console.log(divNode.childNodes[1].nodeName); //#comment(노드명)
        console.log(divNode.childNodes[2].nodeName); //SPAN(노드명:태그 대문자명)
        //childrent속성은 HTMLCollection타입(엘리먼트 노드(태그)만 담은 컬렉션(유사배열))
        console.log(divNode.children); //▶HTMLCollection [span]
        console.log(divNode.children[0]);
        console.log(divNode.children[0].nodeName); //SPAN(노드명:태그 대문자명)

        var button = document.querySelector("button");
        button.onclick = function () {
          console.log(fieldset.children); //▶HTMLCollection(4) [legend, input.table, input.table, button]
          var row = parseInt(fieldset.children[1].value);
          var column = parseInt(fieldset.children[2].value);
          //1.table 엘리먼트 생성
          var table = document.createElement("table"); //<table></table>
          //table엘리먼트에 속성 추가
          table.setAttribute(
            "style",
            "background-color:black;border-spacing:1px"
          ); //<table style="background-color:black;border-spacing:1px"></table>
          for (var i = 1; i <= row; i++) {
            //2.tr엘리먼트 생성
            var tr = document.createElement("tr");
            //tr.setAttribute('style','background-color:white');
            tr.style = "background-color:white";
            for (var k = 1; k <= column; k++) {
              //3.td엘리먼트 생성
              var td = document.createElement("td");
              var textNode = document.createTextNode(i + "행 " + k + "열");
              //4.텍스트 노드를 td에 추가
              td.append(textNode);
              //5.생성된 td를 tr에 추가
              tr.append(td);
            }
            //6.tr을 table에 추가
            table.append(tr);
          }
          console.log(table);
          //7.table을 div에 추가
          //divNode.append(table);
          //divNode.appendChild(table);
          //divNode.prepend(table);
          //divNode.insertBefore(table,span);
          //divNode.insertAdjacentElement('afterbegin',table);

          //divNode.insertAdjacentHTML('afterbegin',table);//[object HTMLTableElement] 여기에 표를 위치 시킵니다.식으로 출력된다
          divNode.insertAdjacentHTML("afterbegin", table.outerHTML); //두번째 인자는 무조건 string이어야 한다
        };
      });
    </script>
  </head>
  <body>
    <h2>DOM API 사용하기:노드 추가하기</h2>
    <fieldset>
      <legend>표 설정하기</legend>
      <input type="text" class="table" /> 행&nbsp;&nbsp;&nbsp;
      <input type="text" class="table" /> 렬
      <button>표만들기</button>
    </fieldset>

    <div class="box">
      <!-- comment --><span>여기에 표를 위치 시킵니다.</span>
    </div>
  </body>
</html>

결과) 

DOM09_2.html

<!DOCTYPE html>
<html lang="ko">
  <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>DOM09_2.html</title>
  </head>
  <body>
    <h2>DOM API 사용하기:노드 삭제하기</h2>
    <fieldset>
      <legend>행 삭제하기</legend>
      <table
        style="
          width: 400px;
          background-color: black;
          border-spacing: 1px;
          text-align: center;
        "
      >
        <tr style="background-color: white">
          <td><input type="checkbox" value="1" /></td>
          <td>1행1열</td>
          <td>1행2열</td>
          <td>1행3열</td>
        </tr>
        <tr style="background-color: white">
          <td><input type="checkbox" value="2" /></td>
          <td>2행1열</td>
          <td>2행2열</td>
          <td>2행3열</td>
        </tr>
        <tr style="background-color: white">
          <td><input type="checkbox" value="3" /></td>
          <td>3행1열</td>
          <td>3행2열</td>
          <td>3행3열</td>
        </tr>
        <tr style="background-color: white">
          <td><input type="checkbox" value="4" /></td>
          <td>4행1열</td>
          <td>4행2열</td>
          <td>4행3열</td>
        </tr>
        <tr style="background-color: white">
          <td>
            <input type="checkbox" value="5" />
          </td>
          <td>5행1열</td>
          <td>5행2열</td>
          <td>5행3열</td>
        </tr>
      </table>
      <hr />
      <button>행 삭제하기</button>
    </fieldset>
    <script>
      var table = document.querySelector("table");
      var button = document.querySelector("button");

      button.addEventListener("click", function () {
        //체크된 체크박스들 얻기
        var checked = table.querySelectorAll("input[type=checkbox]:checked");
        console.log(checked); //▶NodeList(2) [input, input]
        checked.forEach(function (item, index) {
          console.log("value:%s,index:%s", item.value, index);
          //item.remove();//체크박스 삭제
          //체크박스의 조부인 tr노드를 삭제해야 한다
          console.log(item.parentElement.parentElement);
          item.parentElement.parentElement.remove();
        });
      });
    </script>
  </body>
</html>

결과)

 

이벤트 더블링: 부모에게 이벤트를 걸면 자식에게 이벤트가 전파가 됨

DOM09_3.html

<!DOCTYPE html>
<html lang="ko">
  <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>DOM09_3.html</title>
    <script>
      window.addEventListener("DOMContentLoaded", function () {
        var ul = document.querySelector("ul");
        var buttonUp = document.querySelector(".up");
        var buttonDown = document.querySelector(".down");

        var li = null; //클릭한 LI를 담는 변수

        //li의 부모인 ul에 이벤트 바인딩(리스터 부착)
        ul.onclick = function (e) {
          console.log(e.target.nodeName);
          if (e.target.nodeName === "LI") {
            if (li !== null) li.style.backgroundColor = "white";
            //클릭한 li의 배경색 설정
            e.target.style.backgroundColor = "green";
            //변수 li를 클릭한 li로 변경
            li = e.target;
          }
        };

        buttonUp.onclick = function () {
          if (li === null) {
            alert("메뉴를 클릭하세요");
            return;
          }
          var previous = li.previousElementSibling;
          console.log("previous:", previous);
          if (previous === null) {
            alert("이전 메뉴가 없어요");
            return;
          }
          li.insertAdjacentElement("afterend", previous);
        };

        buttonDown.onclick = function () {
          if (li === null) {
            alert("메뉴를 클릭하세요");
            return;
          }
          var next = li.nextElementSibling;
          if (next === null) {
            alert("다음 메뉴가 없어요");
            return;
          }
          li.insertAdjacentElement("beforebegin", next);
        };
      });
    </script>
  </head>
  <body>
    <h2>DOM API 사용하기:노드의 위치 바꾸기</h2>
    <fieldset style="width: 60%">
      <legend>메뉴 위치 변경하기</legend>
      <ul>
        <li>메뉴1</li>
        <li>메뉴2</li>
        <li>메뉴3</li>
        <li>메뉴4</li>
        <li>메뉴5</li>
        <li>메뉴6</li>
      </ul>
      <button class="up">위로</button>
      <button class="down">아래로</button>
    </fieldset>
  </body>
</html>

결과) 메뉴 3 클릭 시 바탕색이 녹색, 

위로 버튼 클릭 시 위로 올라감. 최대한으로 올라가서 더 누르면 알람이 호출됨

아래로 버튼 클릭 시 아래로 올라감. 최대한으로 내려가서 더 누르면 알람이 호출됨

'JavaScript' 카테고리의 다른 글

35일차 2023-04-25  (0) 2023.04.25
34일차 2023-04-24  (0) 2023.04.24
32일차 2023-04-20  (1) 2023.04.20
31일차 2023-04-19  (0) 2023.04.19
30일차 2023-04-18  (0) 2023.04.18