[JS] DOM 다루기, MutationObserver

merci·2023년 9월 5일
0

querySelector

태그 이름으로 찾기

document.querySelectorAll(':not(th)')

document.querySelectorAll('#fileList tbody tr:not(.sampleRow, #noFile)')

selected

document.querySelector('#encodingForm select[name="encStatus"]').value
$('#form').find('select[name="name"]').val();

input -> 체크항목 찾기

table.querySelectorAll('input[type="radio"]:checked')

class 이름으로 찾기

let originString = target.querySelector('[class="t1"]').textContent;

태그 내부의 class 이름으로 찾기

trElem.querySelector('button.tree-file')

태그의 속성으로 찾기

this.#target.querySelector('input[data-all-check]')


classList

class 이름 교체

el.classList.replace('show', 'hide')

태그의 class 에서 찾기

  • 테이블의 내부 로우를 삭제하고 싶을때
      tbody?.querySelectorAll('tr').forEach((item) => {
          if (item.classList.contains('no-data')) {
              while (tbody.firstChild) {
                  tbody.removeChild(tbody.firstChild);
              }
          }
      })

class 이름 추가

var element = document.querySelector('.some-selector');
element.classList.add('new-class-name');

class 제거

copyRow.classList.remove('sampleRow')


contentWindow, contentDocument

const table = obj.contentWindow.document.getElementById("list-d1");

authTable = e.contentWindow.document.getElementById('list') ||
                e.contentDocument.getElementById('ist');


iframe 찾기

[data=keyword]: 속성 data의 값이 정확히 keyword와 일치하는 요소 찾기
[data^=keyword]: 속성 data의 값이 keyword로 시작하는 요소 찾기
[data$=keyword]: 속성 data의 값이 keyword로 끝나는 요소 찾기
[data*=keyword]: 속성 data의 값이 keyword가 포함되는 요소 찾기

const newObject = window.parent?.document?.querySelector("[data*=" + modal + "]")
const footBtns = newObject.contentDocument.querySelectorAll('.modal-pop-foot button');
const boxDocument = window.parent?.document?.querySelector("[data*='/rfidLabel']");

iframe에서 윈도우 reload

window.top.location.reload();

iframe에서 부모 dom 접근

const sidePop = window.parent?.document?.querySelector('.side-pop');
window.parent.document.location.href = CONTEXT_PATH;
window.parent.document.querySelector('#body_content');

브라우저 세션의 임시 URL 생성

  • 업로드한 이미지 썸네일 주소 만들때 사용
let fileUrl = window.URL.createObjectURL(result);


getAttribute, setAttribute, hasAttribute

style과 class 이름으로 찾기 (getAttribute)

      const allObjectTag = parent.document.querySelectorAll('object');
      let authTable = null;
      allObjectTag.forEach((e) => {
          let style = e.getAttribute('style');
          let className = e.getAttribute('class');

          if ((style === null || style.indexOf('z-index') === -1) && 
              (className === null || className.indexOf('on') === -1)) {
              authTable = e.contentWindow.document.getElementById('list') ||
                              e.contentDocument.getElementById('list');
          }
      });

태그 속성으로 찾기 (hasAttribute)

nextElem.hasAttribute('data-parent-code');

태그에 속성 추가 (setAttribute)

target.setAttribute('data-parent-code', parentCode);


getElementById의 단점

document 요소에서만 사용가능함 -> querySelector를 사용하는 이유


polling ( 인터벌 )

      let interval = setInterval(() => {
          if (e.querySelector('#hiddenArr')) {
              clearInterval(interval);  // 폴링 중지

              const item = e.querySelector('#hiddenArr').querySelector('input');

              bldgArr = JSON.parse(item.value)
              console.log(bldgArr)

          } else {
              console.log('대기중');
          }
      }, 10);

append, apendChiled 차이

apendChild는 노드만 추가 가능합니다.
예를 들어 parentElement.appendChild(childNode); 처럼 element를 추가할 때 사용합니다.

반면에 append는 노드와 텍스트를 추가할 때 사용합니다.
parentElement.append(childNode, textNode, 'text')

dom 추적 MutationObserver

자식 변화 감지

        // 사이드뷰가 닫히면 실행시킬 함수
        const targetNode = parent.document?.querySelector("[data*='/detail']")
        const observer = new MutationObserver(function(mutationsList) {
            for (let mutation of mutationsList) {
                if (mutation.type === 'childList') {
                    // Object 태그가 DOM에서 사라졌는지 확인
                    if (!parent.document.contains(targetNode)) {
                        searchRtFnc();
                        observer.disconnect();
                        break;
                    }
                }
            }
        });

        observer.observe(parent.document, { childList: true, subtree: true }); // 자식 노드 관찰, 하위 노드 관찰

속성 변화 감지

    const observer2 = new MutationObserver(function(mutationsList) {
            for (let mutation of mutationsList) {
                // 자신의 속성 변화 감지
                if (mutation.type === 'attributes') {
                    if (mutation.attributeName === 'style') {
                        
                    }
                }
            }
        });

    observer2.observe(target, { attributes: true });
profile
작은것부터

0개의 댓글