HTML DOM의 write() 메서드는 여러 개의 표현식(HTML 또는 JavaScript 코드)을 현재 문서(document)에 직접 작성하고 출력할 수 있는 기능을 제공합니다. 인수는 한 번에 여러 개 전달할 수 있으며, 전달된 순서대로 문서에 기록됩니다.
참고: 이 메서드는 문서에 이미 HTML 코드가 존재하는 경우 해당 내용을 덮어씁니다(overwrite). 또한 인수를 자동으로 새 줄에 추가하지 않으므로, 줄바꿈이 필요하다면 직접 처리해야 합니다.
구문(Syntax)
write() 메서드의 기본 구문은 다음과 같습니다.
document.write(arg1, arg2, ...)
예제(Example)
아래 예제는 HTML DOM document.write() 메서드를 활용하여, 새로 연 창(window)에 입력된 사용자 이름의 권한 여부에 따라 서로 다른 내용을 출력하는 코드입니다.
<!DOCTYPE html>
<html>
<head>
<title>HTML DOM write()</title>
<style>
* {
padding: 2px;
margin:5px;
}
form {
width:70%;
margin: 0 auto;
text-align: center;
}
input[type="button"] {
border-radius: 10px;
</style>
</head>
<body>
<form>
<fieldset>
<legend>HTML-DOM-write( )</legend>
<input id="urlSelect" type="url" placeholder="Type URL here..."><br>
<input id="textSelect" type="text" placeholder="Full Name"><br>
<input type="button" value="Go To" onclick="openWindow()">
<input type="button" value="Close" onclick="closeWindow()">
<input type="button" value="Restore" onclick="restoreWindow()">
<div id="divDisplay"></div>
</fieldset>
</form>
<script>
var urlSelect = document.getElementById("urlSelect");
var textSelect = document.getElementById("textSelect");
var winSource;
function openWindow() {
browseWindow = window.open(urlSelect.value, "browseWindow", "width=400, height=200");
winSource = urlSelect.value;
browseWindow.opener.document.getElementById("divDisplay").textContent = "Child Window Active";
if(textSelect.value !== 'admin')
browseWindow.document.write("<p><strong>Unauthorized User:</strong></p>","<p>"+textSelect.value+"</p>");
}
function closeWindow(){
if(browseWindow){
browseWindow.close();
browseWindow.opener.document.getElementById("divDisplay").textContent = "Child Window Closed";
}
}
function restoreWindow(){
if(browseWindow.closed){
browseWindow = window.open(winSource, "browseWindow", "width=400, height=200");
browseWindow.opener.document.getElementById("divDisplay").textContent = "Child Window Restored";
}
}
</script>
</body>
</html>실행 결과(Output)
'Go To' 버튼을 권한이 없는 이름(Full Name)을 입력한 상태에서 클릭하면, 새로 열린 창에 'Unauthorized User'라는 경고 메시지와 함께 입력한 이름이 출력됩니다.

반대로 권한이 있는 이름('admin')을 입력한 상태에서 클릭하면 경고 메시지 없이 정상적으로 해당 URL의 페이지가 열립니다.

함께 알아두면 좋은 점
- writeln() 메서드는 write()와 거의 동일하게 동작하지만, 각 인수 뒤에 줄바꿈 문자(\n)를 추가한다는 차이가 있습니다.
- 페이지 로딩이 완료된 후 document.write()를 호출하면 기존 문서 전체가 지워질 수 있으므로 주의해야 합니다.
- 현대적인 웹 개발에서는 textContent, innerHTML 같은 DOM 조작 방식이 권장되며, document.write()는 테스트나 디버깅 목적으로만 제한적으로 사용하는 것이 좋습니다.