Document Object Model ( DOM )은 W3C 에서 권고되고있는 HTML 문서 또는 XML 문서를 응용 프로그램 에서 이용하기위한 API 이다. Level 1 ~ Level 3까지 권고되고있다.
XML을 로드할 다른 API 인 SAX 와 달리 XML 데이터를 트리 구조 로 취급할 수있다. 그러나 보통의 경우 대상의 XML 문서를 모두 로드한 후 처리를 전제로하는 속도가 느리거나 메모리 사용량이 커지는 단점이있다.
W3C에서는 API의 사양을 정의하고있을뿐, 특정 프로그램 언어 를 대상으로 한 것은 아니다. DOM 구현은 각 메이커에 맡길 수있어 DOM을 구현하는 XML 파서 가 각 제조사에서 제공되고있다.
목차[ 숨기기 ] |
권고 [ 편집 ]
W3C는 Level 1에서 Level 3까지 권고되고 있으며, XML 문서를 취급하는 "Core"HTML 문서를 취급하는 "HTML"등의 모듈로 구성되어있다.
Level 1 [ 편집 ]
Level 2 [ 편집 ]
- Document Object Model (DOM) Level 2 Core Specification
- XML 1.0을 취급하는 기본적인 메소드와 네임 스페이스에 대한 확장
- Document Object Model (DOM) Level 2 HTML Specification
- Document Object Model (DOM) Level 2 Views Specification
- 보기 에 대한 확장
- Document Object Model (DOM) Level 2 Style Specification
- Document Object Model (DOM) Level 2 Events Specification
- Document Object Model (DOM) Level 2 Traversal and Range Specification
- DOM 트리의 횡단과 DOM 트리의 조작 범위에 대한 확장
Level 3 [ 편집 ]
- Document Object Model (DOM) Level 3 Core Specification
- XML 1.0을 취급하는 기본적인 메소드와 네임 스페이스에 대한 확장.
- Document Object Model (DOM) Level 3 Load and Save Specification
- DOM 트리를 읽고
- Document Object Model (DOM) Level 3 Validation Specification
- DOM 트리에 포함된 스키마 정의 편집
관련 [ 편집 ]
외부 링크 [ 편집 ]
- Document Object Model (DOM) Specifications - W3C
- DOM에 대해
- Gecko DOM Reference
- DOM Central - Netscape DevEdge
문서 객체 모델(DOM; Document Object Model)은 객체 지향 모델로써 구조화된 문서를 표현하는 형식이다. DOM은 플랫폼/언어 중립적으로 구조화된 문서를 표현하는 W3C의 공식 표준이다. DOM은 또한 W3C가 표준화한 여러 개의API의 기반이 된다.
DOM은 HTML 문서의 요소를 제어하기 위해 웹 브라우저에서 처음 지원되었다. DOM은 동적으로 문서의 내용, 구조, 스타일에 접근하고 변경하는 수단이었다. 브라우저 사이에 DOM 구현이 호환되지 않음에 따라, W3C에서 DOM 표준 규격을 작성하게 되었다.
DOM은 문서의 기반이 되는 데이터 구조에 제한을 두지 않는다. 잘 구조화된 문서는 DOM을 사용하여 트리 구조를 얻어낼 수 있다. 대부분의 XML 해석기와 XSL 처리기는 트리 구조의 이용에 대응해 개발되었다. 이 같은 구현에서는 문서의 전체 내용이 해석되어 메모리 저장되어야 한다. 때문에 DOM은 문서 요소가 임의적으로 접근되고 변경할 수 있어야 하는 응용 프로그램에 가장 적합하다. 한 번 해석 시 단 한 번의 선택적 읽기/쓰기가 이루어지는 XML 기반 응용 프로그램에서, DOM은 메모리에 상당한 부하를 가져온다. 이 경우처럼 속도와 효율적인 메모리 소비가 중요한 상황일 경우SAX 모델이 장점을 가진다.
목차[숨기기] |
[편집]DOM 단계
현행의 DOM 규격은 단계 2이다. 그러나 일부 단계 3 규격 역시 현재 W3C의 권고안이다.
- 단계 0
- DOM이 만들어지기 이전의 모든 벤더 종속적인 DOM을 포함한다. 예: document.images, document.forms,document.layers, document.all. 그러나 이것은 W3C이 공식적으로 공개한 규격이 아니며, 표준화 이전에 있던 단계를 말한다.
- 단계 1
- DOM 문서에 대한 탐색과 조정
- 단계 2
- XML 명칭 공간(네임스페이스; namespace) 지원, 필터링된 뷰(view)와 DOM 이벤트.
- 단계 3
- 6가지 다른 규격으로 구성: 1) DOM 단계 3 코어. 2) DOM 단계 3 불러와서 저장(Load and Save). 3) DOM 단계 3 XPath. 4) DOM 단계 3 보기 및 초기화(formatting). 5) DOM 단계 3 요구사항. 6) DOM 단계 3 유효 확인.
[편집]웹 브라우저간의 비호환 문제
브라우저간의 DOM 구현의 차이 때문에 상호 운용성 문제가 생기게 되었다.
마이크로소프트의 인터넷 익스플로러 브라우저는 2005년 현재 사실상의 표준 웹 브라우저의 위치를 차지하고 있기 때문에, 모질라와 같이 표준을 준수하는 브라우저에 대한 개발에 곤란한 문제가 된다. 만약 개발자가 마이크로소프트의 DOM 확장을 사용한다면 표준 준수에 대한 신뢰성을 잃을 수 있으며, 반대의 경우라면 비표준 확장을 사용하지 않음으로 생기는 기능적 제약 때문에 사용자가 이탈할 수도 있다. 얄궂게도 마이크로소프트와 넷스케이프 양쪽 다 표준 경쟁의 와중에서 비표준 기능을 퍼트리게 된 것에 대한 책임을 피할 수 없다. 더구나 최근의 상황을 빼면, 역사적으로 언제나 인터넷 익스플로러의 표준 지원이 넷스케이프의 그것에 비해 우위에 있었다.
만약 표준 호환 브라우저가 웹 시장에서 주목할 만한 점유율을 차지하게 된다면 이 같은 상황이 바뀌게 될 것이며, 비표준 확장을 사용하는 것이 작성자에게 상업적 불이익으로 다가올 것이라는 것에 대해서는 일반적으로 의견이 일치하고 있다.
[편집]기술 규격
- DOM 단계 1 기술 규격
- 단계 2 권고안:
- 단계 3 권고안:
- 단계 3 작업 그룹 노트:
[편집]같이 보기
- 문서 객체 모델 이벤트
- SAX - 순차적 방법으로 XML 문서에 접근/수정하는 API 집합
- JDOM - DOM, SAX, 그리고 문서를 작성을 위한 사용자 해석기를 통합한 XML용 자바 기반 문서 객체 모델
[편집]바깥 고리
출처 - http://ko.wikipedia.org/wiki/%EB%AC%B8%EC%84%9C_%EA%B0%9D%EC%B2%B4_%EB%AA%A8%EB%8D%B8
With the HTML DOM, JavaScript can access and change all the elements of an HTML document.
The HTML DOM (Document Object Model)
When a web page is loaded, the browser creates a Document Object Model of the page.
The HTML DOM model is constructed as a tree of Objects:
The HTML DOM Tree of Objects
With the object model, JavaScript gets all the power it needs to create dynamic HTML:
- JavaScript can change all the HTML elements in the page
- JavaScript can change all the HTML attributes in the page
- JavaScript can change all the CSS styles in the page
- JavaScript can remove existing HTML elements and attributes
- JavaScript can add new HTML elements and attributes
- JavaScript can react to all existing HTML events in the page
- JavaScript can create new HTML events in the page
What You Will Learn
In the next chapters of this tutorial you will learn:
- How to change the content of HTML elements
- How to change the style (CSS) of HTML elements
- How to react to HTML DOM events
- How to add and delete HTML elements
What is the DOM?
The DOM is a W3C (World Wide Web Consortium) standard.
The DOM defines a standard for accessing documents:
"The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document."
The W3C DOM standard is separated into 3 different parts:
- Core DOM - standard model for all document types
- XML DOM - standard model for XML documents
- HTML DOM - standard model for HTML documents
What is the HTML DOM?
The HTML DOM is a standard object model and programming interface for HTML. It defines:
- The HTML elements as objects
- The properties of all HTML elements
- The methods to access all HTML elements
- The events for all HTML elements
In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML elements.
HTML DOM methods are actions you can perform (on HTML Elements)
HTML DOM properties are values (of HTML Elements) that you can set or change
The DOM Programming Interface
The HTML DOM can be accessed with JavaScript (and with other programming languages).
In the DOM, all HTML elements are defined as objects.
The programming interface is the properties and methods of each object.
A property is a value that you can get or set (like changing the content of an HTML element).
A method is an action you can do (like add or deleting an HTML element).
Example
The following code gets the content (the innerHTML) of the <p> element with id="intro":
Example
<body>
<p id="intro">Hello World!</p>
<script>
var txt=document.getElementById("intro").innerHTML;
document.write(txt);
</script>
</body>
</html>
Try it yourself »
In the example above, getElementById is a method, while innerHTML is a property.
The getElementById Method
The most common way to access an HTML element is to use the id of the element.
In the example above the getElementById method used id="intro" to find the element.
The innerHTML Property
The easiest way to get the content of an element is by using the innerHTML property.
The innerHTML property is useful for getting or replacing the content of HTML elements.
The innerHTML property can be used to get or change any HTML element, including <html> and <body>. |
With the HTML DOM, the document object is your web page.
The HTML DOM Document
In the HTML DOM object model, the document object represents your web page.
The document object is the owner of all other objects in your web page.
If you want to access objects in an HTML page, you always start with accessing the document object.
Below are some examples of how you can use the document object to access and manipulate HTML.
The next chapters demonstrate all the methods.
Finding HTML Elements
Method | Description |
---|---|
document.getElementById() | Finding an element by element id |
document.getElementsByTagName() | Finding elements by tag name |
document.getElementsByClassName() | Finding elements by class name |
document.forms[] | Finding elements by HTML element objects |
Changing HTML Elements
Method | Description |
---|---|
document.write(text) | Writing into the HTML output stream |
document.getElementById(id).innerHTML= | Changing the inner HTML of an element |
document.getElementById(id).attribute= | Changing the attribute of an element |
document.getElementById(id).style.attribute= | Changing the style of an HTML element |
Adding and Deleting Elements
Method | Description |
---|---|
document.createElement() | Create an HTML element |
document.removeChild() | Remove an HTML element |
document.appendChild() | Add an HTML element |
document.replaceChild() | replace an HTML element |
Adding Events Handlers
Method | Description |
---|---|
document.getElementById(id).onclick=function(){code} | Adding event handler code to an onclick event |
This page teaches you how to find and access HTML elements in an HTML page.
Finding HTML Elements
Often, with JavaScript, you want to manipulate HTML elements.
To do so, you have to find the elements first. There are a couple of ways to do this:
- Finding HTML elements by id
- Finding HTML elements by tag name
- Finding HTML elements by class name
- Finding HTML elements by HTML object collections
Finding HTML Elements by Id
The easiest way to find HTML elements in the DOM, is by using the element id.
This example finds the element with id="intro":
If the element is found, the method will return the element as an object (in x).
If the element is not found, x will contain null.
Finding HTML Elements by Tag Name
This example finds the element with id="main", and then finds all <p> elements inside "main":
Finding HTML Elements by Class Name
If you want to find all HTML elements with the same class name. Use this method:
The example above returns a list of all elements with class="intro".
Finding elements by class name does not work in Internet Explorer 5,6,7, and 8. |
Finding HTML Elements by HTML Object Collections
This example finds the form element with id="frm1", in the forms collection, and displays all element values:
Example
var txt = "";
for (var i=0;i<x.length;i++)
{
txt = txt + x.elements[i].value + "<br>";
}
document.getElementById("demo").innerHTML=txt;
Try it yourself »
The following HTML object collections are accesible:
- document.anchors
- document.forms
- document.images
- document.links
The HTML DOM allows JavaScript to change the content of HTML elements.
Changing the HTML Output Stream
JavaScript can create dynamic HTML content:
Date: Thu Mar 06 2014 23:53:07 GMT+0900 (KST)
In JavaScript, document.write() can be used to write directly to the HTML output stream:
Example
<html>
<body>
<script>
document.write(Date());
</script>
</body>
</html>
Try it yourself »
Never use document.write() after the document is loaded. It will overwrite the document. |
Changing HTML Content
The easiest way to modify the content of an HTML element is by using the innerHTML property.
To change the content of an HTML element, use this syntax:
This example changes the content of a <p> element:
Example
<body>
<p id="p1">Hello World!</p>
<script>
document.getElementById("p1").innerHTML="New text!";
</script>
</body>
</html>
Try it yourself »
This example changes the content of an <h1> element:
Example
<html>
<body>
<h1 id="header">Old Header</h1>
<script>
var element=document.getElementById("header");
element.innerHTML="New Header";
</script>
</body>
</html>
Try it yourself »
Example explained:
- The HTML document above contains an <h1> element with id="header"
- We use the HTML DOM to get the element with id="header"
- A JavaScript changes the content (innerHTML) of that element
Changing the Value of an Attribute
To change the value of an HTML attribute, use this syntax:
This example changes the value of the src attribute of an <img> element:
Example
<html>
<body>
<img id="image" src="smiley.gif">
<script>
document.getElementById("image").src="landscape.jpg";
</script>
</body>
</html>
Try it yourself »
Example explained:
- The HTML document above contains an <img> element with id="image"
- We use the HTML DOM to get the element with id="image"
- A JavaScript changes the src attribute of that element from "smiley.gif" to "landscape.jpg"
The HTML DOM allows JavaScript to change the style of HTML elements.
Changing HTML Style
To change the style of an HTML element, use this syntax:
The following example changes the style of a <p> element:
Example
<body>
<p id="p2">Hello World!</p>
<script>
document.getElementById("p2").style.color="blue";
</script>
<p>The paragraph above was changed by a script.</p>
</body>
</html>
Try it yourself »
Using Events
The HTML DOM allows you to execute code when an event occurs.
Events are generated by the browser when "things happen" to HTML elements:
- An element is clicked on
- The page has loaded
- Input fields are changed
You will learn more about events in the next chapter of this tutorial.
This example changes the style of the HTML element with id="id1", when the user clicks a button:
Example
<html>
<body>
<h1 id="id1">My Heading 1</h1>
<button type="button"
onclick="document.getElementById('id1').style.color='red'">
Click Me!</button>
</body>
</html>
Try it yourself »
More Examples
Visibility How to make an element invisible. Do you want the element to show or not?
HTML DOM Style Object Reference
For all HTML DOM style properties, look at our complete HTML DOM Style Object Reference.
HTML DOM allows JavaScript to react to HTML events.
Example
Reacting to Events
A JavaScript can be executed when an event occurs, like when a user clicks on an HTML element.
To execute code when a user clicks on an element, add JavaScript code to an HTML event attribute:
Examples of HTML events:
- When a user clicks the mouse
- When a web page has loaded
- When an image has been loaded
- When the mouse moves over an element
- When an input field is changed
- When an HTML form is submitted
- When a user strokes a key
In this example, the content of the <h1> element is changed when a user clicks on it:
Example
<html>
<body>
<h1 onclick="this.innerHTML='Ooops!'">Click on this text!</h1>
</body>
</html>
Try it yourself »
In this example, a function is called from the event handler:
Example
<html>
<head>
<script>
function changetext(id)
{
id.innerHTML="Ooops!";
}
</script>
</head>
<body>
<h1 onclick="changetext(this)">Click on this text!</h1>
</body>
</html>
Try it yourself »
HTML Event Attributes
To assign events to HTML elements you can use event attributes.
Example
Assign an onclick event to a button element:
Try it yourself »
In the example above, a function named displayDate will be executed when the button is clicked.
Assign Events Using the HTML DOM
The HTML DOM allows you to assign events to HTML elements using JavaScript:
Example
Assign an onclick event to a button element:
document.getElementById("myBtn").onclick=function(){displayDate()};
</script>
Try it yourself »
In the example above, a function named displayDate is assigned to an HTML element with the id="myBtn".
The function will be executed when the button is clicked.
The onload and onunload Events
The onload and onunload events are triggered when the user enters or leaves the page.
The onload event can be used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information.
The onload and onunload events can be used to deal with cookies.
The onchange Event
The onchange event are often used in combination with validation of input fields.
Below is an example of how to use the onchange. The upperCase() function will be called when a user changes the content of an input field.
The onmouseover and onmouseout Events
The onmouseover and onmouseout events can be used to trigger a function when the user mouses over, or out of, an HTML element.
The onmousedown, onmouseup and onclick Events
The onmousedown, onmouseup, and onclick events are all parts of a mouse-click. First when a mouse-button is clicked, the onmousedown event is triggered, then, when the mouse-button is released, the onmouseup event is triggered, finally, when the mouse-click is completed, the onclick event is triggered.
More Examples
onmousedown and onmouseup
Change an image when a user holds down the mouse button.
onload
Display an alert box when the page has finished loading.
onfocus
Change the background-color of an input field when it gets focus.
Mouse Events
Change the color of an element when the cursor moves over it.
HTML DOM Event Object Reference
For a list of all HTML DOM events, look at our complete HTML DOM Event Object Reference.
With the HTML DOM, you can navigate the node tree using node relationships.
DOM Nodes
According to the W3C HTML DOM standard, everything in an HTML document is a node:
- The entire document is a document node
- Every HTML element is an element node
- The text inside HTML elements are text nodes
- Every HTML attribute is an attribute node
- All comments are comment nodes
With the HTML DOM, all nodes in the node tree can be accessed by JavaScript.
New nodes can be created, and all nodes can be modified or deleted.
Node Relationships
The nodes in the node tree have a hierarchical relationship to each other.
The terms parent, child, and sibling are used to describe the relationships.
- In a node tree, the top node is called the root (or root node)
- Every node has exactly one parent, except the root (which has no parent)
- A node can have a number of children
- Siblings (brothers or sisters) are nodes with the same parent
<head>
<title>DOM Tutorial</title>
</head>
<body>
<h1>DOM Lesson one</h1>
<p>Hello world!</p>
</body>
</html>
From the HTML above you can read:
- <html> is the root node
- <html> has no parents
- <html> is the parent of <head> and <body>
- <head> is the first child of <html>
- <body> is the last child of <html>
and:
- <head> has one child: <title>
- <title> has one child (a text node): "DOM Tutorial"
- <body> has two children: <h1> and <p>
- <h1> has one child: "DOM Lesson one"
- <p> has one child: "Hello world!"
- <h1> and <p> are siblings
Navigating Between Nodes
You can use the following node properties to navigat between nodes with JavaScript:
- parentNode
- childNodes[nodenumber]
- firstChild
- lastChild
- nextSibling
- previousSibling
Warning !
A common error in DOM processing is to expect an element node to contain text.
In this example: <title>DOM Tutorial</title>, the element node <title> does not contain text. It contains a text node with the value "DOM Tutorial".
The value of the text node can be accessed by the node's innerHTML property, or the nodeValue.
Child Nodes and Node Values
In addition to the innerHTML property, you can also use the childNodes and nodeValue properties to get the content of an element.
The following code gets the value of the <p> element with id="intro":
Example
<body>
<p id="intro">Hello World!</p>
<script>
var txt=document.getElementById("intro").childNodes[0].nodeValue;
document.write(txt);
</script>
</body>
</html>
Try it yourself »
In the example above, getElementById is a method, while childNodes and nodeValue are properties.
In this tutorial we use the innerHTML property. However, learning the method above is useful for understanding the tree structure and the navigation of the DOM.
Using the firstChild property is the same as using childNodes[0]:
Example
<body>
<p id="intro">Hello World!</p>
<script>
txt=document.getElementById("intro").firstChild.nodeValue;
document.write(txt);
</script>
</body>
</html>
Try it yourself »
DOM Root Nodes
There are two special properties that allow access to the full document:
- document.documentElement - The full document
- document.body - The body of the document
Example
<body>
<p>Hello World!</p>
<div>
<p>The DOM is very useful!</p>
<p>This example demonstrates the <b>document.body</b> property.</p>
</div>
<script>
alert(document.body.innerHTML);
</script>
</body>
</html>
Try it yourself »
The nodeName Property
The nodeName property specifies the name of a node.
- nodeName is read-only
- nodeName of an element node is the same as the tag name
- nodeName of an attribute node is the attribute name
- nodeName of a text node is always #text
- nodeName of the document node is always #document
Note: nodeName always contains the uppercase tag name of an HTML element.
The nodeValue Property
The nodeValue property specifies the value of a node.
- nodeValue for element nodes is undefined
- nodeValue for text nodes is the text itself
- nodeValue for attribute nodes is the attribute value
The nodeType Property
The nodeType property returns the type of node. nodeType is read only.
The most important node types are:
Element type | NodeType |
---|---|
Element | 1 |
Attribute | 2 |
Text | 3 |
Comment | 8 |
Document | 9 |
Adding and Removing Nodes (HTML Elements)
Creating New HTML Elements (Nodes)
To add a new element to the HTML DOM, you must create the element (element node) first, and then append it to an existing element.
Example
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var para=document.createElement("p");
var node=document.createTextNode("This is new.");
para.appendChild(node);
var element=document.getElementById("div1");
element.appendChild(para);
</script>
Try it yourself »
Example Explained
This code creates a new <p> element:
To add text to the <p> element, you must create a text node first. This code creates a text node:
Then you must append the text node to the <p> element:
Finally you must append the new element to an existing element.
This code finds an existing element:
This code appends the new element to the existing element:
Creating new HTML Elements - insertBefore()
The appendChild() method in the previous example, appended the new element as the last child of the parent.
If you don't want that you can use the insertBefore() method:
Example
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var para=document.createElement("p");
var node=document.createTextNode("This is new.");
para.appendChild(node);
var element=document.getElementById("div1");
var child=document.getElementById("p1");
element.insertBefore(para,child);
</script>
Try it yourself »
Removing Existing HTML Elements
To remove an HTML element, you must know the parent of the element:
Example
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var parent=document.getElementById("div1");
var child=document.getElementById("p1");
parent.removeChild(child);
</script>
Try it yourself »
Example Explained
This HTML document contains a <div> element with two child nodes (two <p> elements):
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
Find the element with id="div1":
Find the <p> element with id="p1":
Remove the child from the parent:
It would be nice to be able to remove an element without referring to the parent. But sorry. The DOM needs to know both the element you want to remove, and its parent. |
Here is a common workaround: Find the child you want to remove, and use its parentNode property to find the parent:
child.parentNode.removeChild(child);
Replacing HTML Elements
To replace an element to the HTML DOM, use the replaceChild() method:
Example
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var para=document.createElement("p");
var node=document.createTextNode("This is new.");
para.appendChild(node);
var parent=document.getElementById("div1");
var child=document.getElementById("p1");
parent.replaceChild(para,child);
</script>
Try it yourself »
A nodelist is an array of nodes (like an array of all HTML elements)
HTML DOM Node List
The getElementsByTagName() method returns a node list. A node list is an array of nodes.
The following code selects all <p> nodes in a document:
Example
The nodes can be accessed by index number. To access the second <p> you can write:
Try it yourself »
Note: The index starts at 0.
HTML DOM Node List Length
The length property defines the number of nodes in a node-list.
You can loop through a node-list by using the length property:
Example
for (i=0;i<x.length;i++)
{
document.write(x[i].innerHTML);
document.write("<br />");
}
Try it yourself »
Example explained:
- Get all <p> element nodes
- For each <p> element, output the value of its text node
출처 - http://www.w3schools.com/js/js_htmldom.asp
'Development > HTML' 카테고리의 다른 글
html - <meta> http-equiv Attribute, X-UA-Compatible (0) | 2014.04.29 |
---|---|
html - content type (0) | 2014.04.15 |
html - 웹킷(webkit) (1) | 2013.12.10 |
html - iframe 안에서 밖으로 자바스크립트 통신하기 (0) | 2013.07.27 |
html5 - hashchange 이벤트 (0) | 2013.06.25 |