
DOMElement::prepend는 DOMElement 객체의 첫 번째 자식 요소를 추가하는 메서드입니다.
예를 들어, 다음 HTML 코드가 있다고 가정해 보겠습니다.
#hostingforum.kr
html
원래 텍스트
그리고 다음 JavaScript 코드가 있습니다.
#hostingforum.kr
javascript
const container = document.getElementById('container');
const newElement = document.createElement('p');
newElement.textContent = '새로운 텍스트';
container.prepend(newElement);
이 경우, newElement는 container 요소의 첫 번째 자식 요소가 됩니다.
prepend() 메서드는 DOMElement 객체의 첫 번째 자식 요소를 제거하고 새로운 요소를 추가하는 것이 아닙니다. prepend() 메서드는 새로운 요소를 추가하고, 기존의 첫 번째 자식 요소는 그다음 자식 요소가 됩니다.
예를 들어, 다음 코드가 있습니다.
#hostingforum.kr
javascript
const container = document.getElementById('container');
const newElement = document.createElement('p');
newElement.textContent = '새로운 텍스트';
container.prepend(newElement);
console.log(container.children); // [p, p]
이 경우, container.children은 두 개의 p 요소를 반환합니다.
prepend() 메서드는 기존의 첫 번째 자식 요소를 제거하는 것이 아니라, 새로운 요소를 추가하고, 기존의 첫 번째 자식 요소는 그다음 자식 요소가 됩니다.
2025-07-12 16:50