JavaScript (9) !!, DOM 속성/요소 노드 탐색, 태그 생성, 텍스트 조작 (DAY 23)

코딩기록·2024년 11월 8일

Element Nodes(html tag) 접근

파란색은 property key, 보라색은 function임

  • children : 자식 요소 노드 접근
    -- children vs childrenNodes
    : children는 Elements node(=html 태그)만 보여주는 반면, childrenNodes는 텍스트 요소, 주석 노드 등을 포함

  • first(last)ElementChild : 첫(마지막) 자식 요소 노드에 접근
  • parentElement : 부모 html 태그 접근
  • closest('css 선택자') : 부모~조상 요소 노드 접근
  • nextElementSibling, previousElementSibling: 형제 요소 노드 접근
  • querySelector('css 선택자'), querySelectorAll('css 선택자')
  • replaceChild(newTag, $childTag) vs replaceChildren(newTag1, newTag2),replaceWith(newTag2), replaceWith(newTag)

Attribute Node 접근

[전체 접근]

  • getAttribute('title')
  • setAttribute('id','container') : attribute가 기존에 있던 경우 변경, 없던 경우 새로 생성
  • removeAttribute('id') : 삭제
  • hasAttribute('id) : 있는지 여부 조회(true/false 반환)

[클래스에서 클래스 값 "일부"에 접근]

  • $box.classList.add('box', 'green')
  • $box.classList.remove('green')
  • $box.classList.contains('green')
  • $box.classList.toggle('green') : 있으면 삭제, 없으면 생성

TextContent, InnerHTML

  • textContent : (공백 포함) text만 출력

  • innerHTML : (공백 포함) html 태그까지 출력

  • 공백은 trim() 사용하여 제거 가능

    <div id="greet">  
      Hello <span class="highlight">World!</span>
     </div>
     위와 같을 때, 
    
    => textContent 출력값 : Hello World!
       innerHTML 출력값 : Hello <span class="highlight">World!</span>

태그 생성

  1. const $newLi = document.createElement('li');
  2. $newLi.textContent = '넣을 내용'
  3. newLi.append/preprend/before/after(newLi.append/preprend/before/after(newLi);


이벤트

방법 장점 예시 코드
addEventListener - 여러 핸들러 추가 가능
- 구형 브라우저에서 호환성 문제 가능
element.addEventListener('click', handlerFunction);
handlerFunction은 함수 이름만 사용하며, () 없이 쓴다.
HTML 태그에 직접 추가 - JavaScript와 HTML이 혼합되어 유지보수 어려움 <button>Click</button>
이벤트 프로퍼티 (element.onclick) - 하나의 핸들러만 지정 가능 (덮어쓰기) element.onclick = function() { alert('Clicked!'); };



활용

1. !! : 값을 Boolean 타입으로 강제 변환

  • 활용예시 : 값이 0이면 true, 값이 0이 아니면 false를 반환할 때 활용
    function hasChild($tag) {
      // ************* !! : 0이면 false, 나머지는 true 반환해라
      return !!$tag.children.length;
    }

2. ul>li에서 li 한 번에 삭제

(1) $ul.replaceChildren()
(2) ul.forEach(ul.forEach(li => $li.remove());
(3) $ul.innerHTML = '';

헷갈렸던 것들

1. 객체, 배열, DOM에서의 delete 효과

  • 객체 : 프로퍼티 삭제
  • 배열 : 배열 요소 자체를 삭제하지는 않고, 배열 요소의 값을 undefined로 수정
  • DOM : 프로퍼티에만 사용 가능. html 태그의 속성 값은 attributes 관련 함수 사용하여야 함. 프로퍼티 중에서도 textContent 등 일부 프로퍼티에 대해서는 사용 불가(textContent 삭제는 $htmlTag.textContent='')

2. createElement 에서 생성된 태그는 한 번 밖에 참조하지 못함

 => html 태그가 아래와 같을 때, 
   
  <ul id="fruits">
    <li>사과</li>
    <li>바나나</li>
    <li>포도</li>
  </ul>
  
  // id="fruits" 접근 + li 태그 접근
  const $fruits = document.getElementById('fruits');
  const [$apple, $banana, $grape] = $fruits;
  // input 태그 생성
  const $input = document.createElement('input');
  $input.value = $apple.textContent; // input은 textContext가 아닌 value임
  $fruits.replaceChild($input, $apple); // $input 태그 사용 완료
  $grape.replaceWith($input);
  <= !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
     생성한 $input 태그는 한 번만 쓸 수 있으므로, 이 코드를 쓰는 동시에 위에서 $apple 대신 대체했던 $input는 사라지게 됨  

연습문제 헷갈렸던 점

  • input 태그에 초기에 value 속성이 없었을 경우, 사용자가 입력한 값은 $input.style.value.value 프로퍼티에는 저장되지 않고, $input.value 프로퍼티에만 저장됨 경우

  • attributes 말고 밖에 나와 있는 width, fontSize는 초기값으로 고정됨

  • image.style.width에는inline스타일을통해설정된값만보임<br>=>css를통해설정한width의경우,parseInt(window.getComputedStyle(image.style.width 에는 inline 스타일을 통해 설정된 값만 보임<br> => css를 통해 설정한 width의 경우, parseInt(window.getComputedStyle(image).width);을 통해 값 출력 가능

0개의 댓글