Language

[udemy] Web Debeloper DOM

jaewpark 2022. 5. 4. 10:11

문서 객체 모델(The Document Object Model, 이하 DOM)

 

Document.getElementById() (참고)

: 주어진 문자열과 일치하는 id 속성을 가진 요소를 찾고, 이를 나타내는 Element 객체를 반환

<html>
<head>
  <title>getElementById 예제</title>
</head>
<body>
  <p id="para">어떤 글</p>
  <button onclick="changeColor('blue');">blue</button>
  <button onclick="changeColor('red');">red</button>
</body>
</html>
function changeColor(newColor) {
  var elem = document.getElementById('para');
  elem.style.color = newColor;
}
버튼을 누르면, getElementById와 일치한 element의 속성을 바꿀 수 있다.

 

Document.getElementByTagName (참고)

 

Document.querySelector() (참고)

: 제공한 선택자 또는 선택자 뭉치와 일치하는 문서 내 첫 번째 Element를 반환, 일치하는 요소가 없으면 null을 반환

<div id="foo\bar"></div>
<div id="foo:bar"></div>

<script>
  console.log('#foo\bar')             // "#fooar" ('\b'는 백스페이스 컨트롤 문자)
  document.querySelector('#foo\bar')  // 일치하는 요소 없음

  console.log('#foo\\bar')            // "#foo\bar"
  console.log('#foo\\\\bar')          // "#foo\\bar"
  document.querySelector('#foo\\bar') // 첫 번째 <div>

  document.querySelector('#foo:bar')   // 일치하는 요소 없음
  document.querySelector('#foo\\:bar') // 두 번째 <div>
</script>
CSS 구문을 따르지 않는, 예컨대 콜론이나 공백을 포함한 선택자나 ID를 사용해야 하면 반드시  백슬래시("\")를 사용해 해당 문자를 이스케이프해야 합니다. 백슬래시는 JavaScript의 이스케이프 문자이기 때문에, 백슬래시를 문자로 입력하려면 반드시 두 번 이스케이프해야 합니다.

 

스타일 변경

const allLinks = document.querySelectorAll('a');

for (let link of allLinks) {
  link.style.color = 'rgb(0, 108, 134)';
  link.style.textDecorationColor = 'magenta';
  link.style.textDecorationStyle = 'wavy';
}

 

계층이동

parentElement (참고)

nextSibling (참고)

nextElementSibling (참고)

 

Document.createElement() (참고)

Node.appendChild() (참고)

<!DOCTYPE html>
<html>
<head>
  <title>||Working with elements||</title>
</head>
<body>
  <div id="div1">위의 텍스트는 동적으로 추가했습니다.</div>
</body>
</html>
document.body.onload = addElement;

function addElement () {
  // create a new div element
  var newDiv = document.createElement("div");
  // and give it some content
  var newContent = document.createTextNode("환영합니다!");
  // add the text node to the newly created div
  newDiv.appendChild(newContent);

  // add the newly created element and its content into the DOM
  var currentDiv = document.getElementById("div1");
  document.body.insertBefore(newDiv, currentDiv);
}

 

Node.removeChild() (참고)