[JS] DOM : 생성, 조회, 수정

Local Gaji·2023년 5월 27일

JavaScript

목록 보기
12/18
<div class="parent">부모
	<div class="child">자식1</div>
  	텍스트
	<div class="child">자식2</div>
</div>

document.createElement('태그')

새로운 HTML 요소를 "메모리에" 생성하여 반환 (실제로 삽입되지는 않음)

const El = document.createElement('div')

Node.prepend(node) / append(node)

노드를 요소의 첫번째 / 마지막 자식으로 삽입

const parentEl = document.querySelector('.parent') 
const el1 = document.createElement('div')
const el2 = document.createElement('div')

parent.prepend(new Comment('주석'))  // 첫번째 자식으로 주석 삽입
parent.prepend(el1, el2)            // 마지막 자식으로 el1, el2 순서대로 삽입

Element.remove()

요소를 제거

const el = document.querySelector('.child') 
el.remove() 

Element.insertAdjacentElement(위치, 새로운요소)

대상 요소의 지정한 위치에 새로운 요소를 삽입

  • 위치 표현 방법
<!-- beforebegin -->
<div class="target">
  <!-- afterbegin -->
  내용
  <!-- beforeend -->
</div>
<!-- afterend -->
const el = document.querySelector('.child')  // 타겟 요소
const newEl = document.createElement('div')  // 추가할 요소 

el.insertAdjacentElement('beforebegin', newEl) 

Node.insertBefore(새노드, 참조노드)

참조 노드의 이전 형제로 새노드를 삽입
순서가 헷갈림

const el = document.querySelector('.child')  // 참조 노드
const newEl = document.createElement('div')  // 새 노드

el.insertBefore(newEl, el) 

Node1.contains(node2)

node2가 Node1의 후손(또는 본인)인지 확인

const node1 = document.querySelector('.parent')
const node2 = document.querySelector('.child')

node1.contains(node2)          // true
node2.contains(node2)          // true
document.body.contains(node1)  // true

Node.textContent

노드의 모든 텍스트를 얻거나 변경

const el = document.querySelector('.child')
el.textContent           // 자식1
el.textContent = 'gaji'  // 자식1 -> gaji 로 이름 변경

Element.innerHTML

요소의 모든 HTML 내용을 문자로 반환
또는 새로운 HTML 내용으로 변경

const el = document.querySelector('.parent')
el.innerHTML                // <div 어쩌고 내용들 ...
el.innerHTML = `새로운 내용`  // 내용을 변경

Element.dataset

요소의 각 data- 속성 값을 얻거나 지정

const el = document.querySelector('.child')

el.dataset.hello = "Hello!"
el.dataset.object = JSON.stringigy({ a: 1, b: 2 })
<div class="child" data-hello="Hello!" data-object="{"a":1,"b":2}">자식1</div>
el.dataset.hello      // Hello!
el.dataset.object     // JSON {"a":1,"b":2}
JSON.parse(el.dataset.object)  // 객체 { a: 1, b: 2 }

Element.tagName

요소의 태그 이름을 반환

const el = document.querySelector('.child')

el.tagName             // DIV
document.body.tagName  // BODY 

Element.id / className

요소의 id / class 속성 값을 얻거나 지정

const el = document.querySelector('.child')

el.id = 'idChild'
el.id         // idChild
el.className  // child

Element.classList

요소의 class 속성 값을 제어

.add(값) : 값 추가
.remove(값) : 값 제거
.toggle(값) : 값 토글
.contains(값) : 값 있는지 확인

const el = document.querySelector('.child')

el.classList.add('active')     // <div class="child active">
el.classList.remove('active')  // <div class="child">
el.classList.toggle('active')  // 있으면 지움, 없으면 생성

el.classList.contains('active')  // true

Element.style

요소의 css 속성 값을 얻거나 지정 (inline style만)

const el = document.querySelector('.child')

// 개별 지정
el.style.width = '100px'  // 등등..
el.style.width            // 100px

// 한번에 지정하기
Object.assign(el.style, {
  width: '100px',
  backgroundColor: 'green'
})

CSS inline style 우선순위는 높음 (동적 지정일때만 사용)

window.getComputedStyle()

요소에 적용된 스타일 객체를 반환 (CSS 파일 등등..)

const el = document.querySelector('.child')

window.getComputedStyle(el)         // 객체
window.getComputedStyle(el).width   // width 속성 값

Element.getAttribute(속성) / getAttribute(속성, 값)

요소의 특정 속성의 값을 얻기 / 지정

const el = document.querySelector('.child')


el.setAttribute('title', 'Hello World')
el.getAttribute('title')  // Hello World

Element.hasAttribute(속성) / removeAttribute(속성)

요소에 특정 속성이 있는지 확인 / 특정 속성을 제거

const el = document.querySelector('.child')

el.hasAttribute('class')     // true
el.removeAttribute('class')

0개의 댓글