原文链接:Introduction to the DOM

Introduction

The Document Object Model, usually referred to as the DOM, is an essential part of making websites interactive. It is an interface that allows a programming language to manipulate the content, structure, and style of a website.

JavaScript is the client-side scripting language that connects to the DOM in an internet browser.

Almost any time a website performs an action, such as rotating between a slideshow of images, displaying an error when a user attempts to submit an incomplete form, or toggling a navigation menu, it is the result of JavaScript accessing and manipulating the DOM.

Note: Although the DOM is language agnostic, or created to be independent from a particular programming language, throughout this resource we will focus on and refer to JavaScript's implementation of the HTML DOM.

Prerequisites

In order to effectively understand the DOM and how it relates to working with the web, it is necessary to have an existing knowledge of HTML and CSS. It is also beneficial to have familiarity with fundamental JavaScript syntax and code structure.

What is the DOM?

At the most basic level, a website consists of an HTML document. The browser that you use to view the website is a program that interprets HTML and CSS and renders the style, content, and structure into the page that you see.

In addition to parsing the style and structure of the HTML and CSS, the browser creates a representation of the document known as the Document Object Model. This model allows JavaScript to access the text content and elements of the website document as objects.

JavaScript is an interactive language, and it is easier to understand new concepts by doing. Let's create a very simple website. Create an index.html and save it in a new project directory.

<!DOCTYPE html>
<html lang="en">
<head>
<title>Learning the DOM</title>
</head> <body>
<h1>Document Object Model</h1>
</body>
</html>

  This code is the familiar HTML source of a new website skeleton. It contains the absolute most essential aspects of a website document - a doctype, and an html tag with the head and bodynested inside

The Document Object

The document object is a built-in object that has many properties and methods that we can use to access and modify websites.

In order to understand how to work with the DOM, you must understand how objects work in JavaScript. Review Understanding Objects in JavaScript if you don't feel comfortable with the concept of objects.

In Developer Tools on index.html, move to the Console tab. Type document into the console and press ENTER.

You will see that what is output is the same as what you see in the Elements tab.

document;

Typing document and otherwise working directly in the console is not something that you'll generally ever do outside of debugging, but it helps solidify exactly what the document object is and how to modify it, as we will discover below.

What is the Difference Between the DOM and HTML Source Code?

Currently, with this example, it seems that HTML source code and the DOM are the exact same thing. There are two instances in which the browser-generated DOM will be different than HTML source code:

  • The DOM is modified by client-side JavaScript
  • The browser automatically fixes errors in the source code

Let's demonstrate how the DOM can be modified by client-side JavaScript.

Type the following into the console:

document.body;

document is an object, body is a property of that object that we have accessed with dot notation. Submitting document.body to the console outputs the body element and everything inside of it.

In the console, we can change some of the live properties of the body object on this website. We'll edit the style attribute, changing the background color to fuchsia. Type this into the console:

document.body.style.backgroundColor = 'fuchsia';

After typing and submitting the above code, you'll see the live update to the site, as the background color changes.

Switching to the Elements tab, or typing document.body into the console again, you will see that the DOM has changed.

Note: In order to change the background-color CSS property, we had to type backgroundColor in the JavaScript. Any hyphenated CSS property will be written in camelCase in JavaScript.

The JavaScript code we typed, assigning fuchsia to the background color of the body, is now a part of the DOM.

However, right click on the page and select "View Page Source". You will notice that the source of the website does not contain the new style attribute we added via JavaScript. The source of a website will not change and will never be affected by client-side JavaScript. If you refresh the page, the new code we added in the console will disappear.

The other instance in which the DOM might have a different output than HTML source code is when there are errors in the source code.

One common example of this is the table tag - a tbody tag is required inside a table, but developers often fail to include it in their HTML. The browser will automatically correct the error and add the tbody, modifying the DOM. The DOM will also fix tags that have not been closed.

Document Object Model (DOM)

The Document Object Model (DOM) connects web pages to scripts or programming languages by representing the structure of a document—such as the HTML representing a web page—in memory. sually that means JavaScript, although modelling HTML, SVG, or XML documents as objects is not part of the JavaScript language, as such.

The DOM represents a document with a logical tree. Each branch of the tree ends in a node, and each node contains objects. DOM methods allow programmatic access to the tree; with them you can change the document's structure, style, or content.

Nodes can also have event handlers attached to them; once an event is triggered, the event handlers get executed.

To learn more about what the DOM is and how it represents documents, see our article introduction to the DOM.

DOM interfaces

Obsolete DOM interfaces

HTML DOM

A document containing HTML is described using the Document interface, which is extended by the HTML specification to include various HTML-specific features. In particular, the Elementinterface is enhanced to become HTMLElement and various subclasses, each representing one of (or a family of closely related) elements.

The HTML DOM API provides access to various browser features such as tabs and windows, CSS styles and stylesheets, browser history, and so forth. These interfaces are discussed further in the HTML DOM API documentation.

SVG interfaces

SVG element interfaces

SVG data type interfaces

Note: Starting in Gecko 5.0, the following SVG-related DOM interfaces representing lists of objects are now indexable and can be accessed; in addition, they have a length property indicating the number of items in the lists: SVGLengthListSVGNumberListSVGPathSegList, and SVGPointList.

Static type

Animated type

SMIL related interfaces

Other SVG interfaces

See also

Introduction to the DOM

The Document Object Model (DOM) is the data representation of the objects that comprise the structure and content of a document on the web.

In this guide, we'll briefly introduce the DOM. We'll look at how the DOM represents an HTML or XML document in memory and how you use APIs to create web content and applications.

What is the DOM?

The Document Object Model (DOM) is a programming interface for HTML and XML documents.

It represents the page so that programs can change the document structure, style, and content.

The DOM represents the document as nodes and objects. That way, programming languages can connect to the page.

A Web page is a document. This document can be either displayed in the browser window or as the HTML source. But it is the same document in both cases.The Document Object Model (DOM) represents that same document so it can be manipulated.

The DOM is an object-oriented representation of the web page, which can be modified with a scripting language such as JavaScript.

The W3C DOM and WHATWG DOM standards are implemented in most modern browsers.

Many browsers extend the standard, so care must be exercised when using them on the web where documents may be accessed by various browsers with different DOMs.

For example, the standard DOM specifies that the getElementsByTagName method in the code below must return a list of all the <P> elements in the document:

var paragraphs = document.getElementsByTagName("p");
// paragraphs[0] is the first <p> element
// paragraphs[1] is the second <p> element, etc.
alert(paragraphs[0].nodeName);

  

All of the properties, methods, and events available for manipulating and creating web pages are organized into objects (for example, the document object that represents the document itself, the table object that implements the special HTMLTableElement DOM interface for accessing HTML tables, and so forth).

This documentation provides an object-by-object reference to the DOM.

The modern DOM is built using multiple APIs that work together.

The core DOM defines the objects that fundamentally describe a document and the objects within it.

This is expanded upon as needed by other APIs that add new features and capabilities to the DOM. For example, the HTML DOM API adds support for representing HTML documents to the core DOM.

DOM and JavaScript

The short example above, like nearly all of the examples in this reference, is JavaScript. That is to say, it's written in JavaScript, but it uses the DOM to access the document and its elements.

The DOM is not a programming language, but without it, the JavaScript language wouldn't have any model or notion of web pages, HTML documents, XML documents, and their component parts (e.g. elements).

Every element in a document—the document as a whole, the head, tables within the document, table headers, text within the table cells—is part of the document object model for that document, so they can all be accessed and manipulated using the DOM and a scripting language like JavaScript.

In the beginning, JavaScript and the DOM were tightly intertwined, but eventually, they evolved into separate entities. The page content is stored in the DOM and may be accessed and manipulated via JavaScript, so that we may write this approximative equation:

API (HTML or XML page) = DOM + JS (scripting language)

The DOM was designed to be independent of any particular programming language, making the structural representation of the document available from a single, consistent API.

Though we focus exclusively on JavaScript in this reference documentation, implementations of the DOM can be built for any language, as this Python example demonstrates:

# Python DOM example
import xml.dom.minidom as m
doc = m.parse(r"C:\Projects\Py\chap1.xml")
doc.nodeName # DOM property of document object
p_list = doc.getElementsByTagName("para")

  For more information on what technologies are involved in writing JavaScript on the web, see JavaScript technologies overview.

Accessing the DOM

You don't have to do anything special to begin using the DOM. Different browsers have different implementations of the DOM, and these implementations exhibit varying degrees of conformance to the actual DOM standard (a subject we try to avoid in this documentation), but every web browser uses some document object model to make web pages accessible via JavaScript.

When you create a script–whether it's inline in a <script> element or included in the web page by means of a script loading instruction–you can immediately begin using the API for the document or window elements to manipulate the document itself or to get at the children of that document, which are the various elements in the web page.

Your DOM programming may be something as simple as the following, which displays an alert message by using the alert() function from the window object, or it may use more sophisticated DOM methods to actually create new content, as in the longer example below.

This following JavaScript will display an alert when the document is loaded (and when the whole DOM is available for use):

<body onload="window.alert('Welcome to my home page!');">

  

Another example. This function creates a new H1 element, adds text to that element, and then adds the H1 to the tree for this document:

<html>
<head>
<script>
// run this function when the document is loaded
window.onload = function() { // create a couple of elements in an otherwise empty HTML page
var heading = document.createElement("h1");
var heading_text = document.createTextNode("Big Head!");
heading.appendChild(heading_text);
document.body.appendChild(heading);
}
</script>
</head>
<body>
</body>
</html>

  

Fundamental data types

This reference tries to describe the various objects and types in simple terms. But there are a number of different data types being passed around the API that you should be aware of.

Note: Because the vast majority of code that uses the DOM revolves around manipulating HTML documents, it's common to always refer to the nodes in the DOM as elements, since in an HTML document, each node is an element. Despite not being strictly accurate, the documentation you'll find on MDN will frequently do the same thing, because of how common this assumption is.

The following table briefly describes these data types.

Data type (Interface) Description
Document When a member returns an object of type document (e.g., the ownerDocument property of an element returns the document to which it belongs), this object is the root document object itself. The DOM documentReference chapter describes the document object.
Node Every object located within a document is a node of some kind. In an HTML document, an object can be an element node but also a text node or attribute node.
Element The element type is based on node. It refers to an element or a node of type element returned by a member of the DOM API. Rather than saying, for example, that the document.createElement() method returns an object reference to a node, we just say that this method returns the element that has just been created in the DOM. element objects implement the DOM Element interface and also the more basic Nodeinterface, both of which are included together in this reference. In an HTML document, elements are further enhanced by the HTML DOM API's HTMLElement interface as well as other interfaces describing capabilities of specific kinds of elements (for instance, HTMLTableElement for <table>elements).
NodeList nodeList is an array of elements, like the kind that is returned by the method document.getElementsByTagName(). Items in a nodeList are accessed by index in either of two ways:

  • list.item(1)
  • list[1]

These two are equivalent. In the first, item() is the single method on the nodeList object. The latter uses the typical array syntax to fetch the second item in the list.

Attribute When an attribute is returned by a member (e.g., by the createAttribute() method), it is an object reference that exposes a special (albeit small) interface for attributes. Attributes are nodes in the DOM just like elements are, though you may rarely use them as such.
NamedNodeMap namedNodeMap is like an array, but the items are accessed by name or index, though this latter case is merely a convenience for enumeration, as they are in no particular order in the list. A namedNodeMap has an item()method for this purpose, and you can also add and remove items from a namedNodeMap.

DOM interfaces

This guide is about the objects and the actual things you can use to manipulate the DOM hierarchy. There are many points where understanding how these work can be confusing.

For example, the object representing the HTML form element gets its name property from the HTMLFormElement interface but its className property from the HTMLElement interface. In both cases, the property you want is simply in that form object.

But the relationship between objects and the interfaces that they implement in the DOM can be confusing, and so this section attempts to say a little something about the actual interfaces in the DOM specification and how they are made available.

Interfaces and Objects

Many objects borrow from several different interfaces.

The table object, for example, implements a specialized HTMLTableElement interface, which includes such methods as createCaption and insertRow. But since it's also an HTML element, table implements the Element interface described in the DOM Element Reference chapter. And finally, since an HTML element is also, as far as the DOM is concerned, a node in the tree of nodes that make up the object model for an HTML or XML page, the table object also implements the more basic Node interface, from which Element derives.

When you get a reference to a table object, as in the following example, you routinely use all three of these interfaces interchangeably on the object, perhaps without knowing it.

var table = document.getElementById("table");
var tableAttrs = table.attributes; // Node/Element interface
for (var i = 0; i < tableAttrs.length; i++) {
// HTMLTableElement interface: border attribute
if(tableAttrs[i].nodeName.toLowerCase() == "border")
table.border = "1";
}
// HTMLTableElement interface: summary attribute
table.summary = "note: increased border";

  

Core Interfaces in the DOM

This section lists some of the most commonly-used interfaces in the DOM. The idea is not to describe what these APIs do here but to give you an idea of the sorts of methods and properties you will see very often as you use the DOM.

These common APIs are used in the longer examples in the DOM Examples chapter at the end of this book.

Document and window objects are the objects whose interfaces you generally use most often in DOM programming.

In simple terms, the window object represents something like the browser, and the document object is the root of the document itself.

Element inherits from the generic Node interface, and together these two interfaces provide many of the methods and properties you use on individual elements. These elements may also have specific interfaces for dealing with the kind of data those elements hold, as in the table object example in the previous section.

The following is a brief list of common APIs in web and XML page scripting using the DOM.

Examples of web and XML development using the DOM

xample 5: Event Propagation

This example demonstrates how events fire and are handled in the DOM in a very simple way.

When the BODY of this HTML document loads, an event listener is registered with the top row of the TABLE.

The event listener handles the event by executing the function stopEvent, which changes the value in the bottom cell of the table.

However, stopEvent also calls an event object method, event.stopPropagation, which keeps the event from bubbling any further up into the DOM.

Note that the table itself has an onclick event handler that ought to display a message when the table is clicked. But the stopEvent method has stopped propagation, and so after the data in the table is updated, the event phase is effectively ended, and an alert box is displayed to confirm this.

<!DOCTYPE html>
<html lang="en">
<head>
<title>Event Propagation</title> <style>
#t-daddy { border: 1px solid red }
#c1 { background-color: pink; }
</style> <script>
function stopEvent(ev) {
c2 = document.getElementById("c2");
c2.innerHTML = "hello"; // this ought to keep t-daddy from getting the click.
ev.stopPropagation();
alert("event propagation halted.");
} function load() {
elem = document.getElementById("tbl1");
elem.addEventListener("click", stopEvent, false);
}
</script>
</head> <body onload="load();"> <table id="t-daddy" onclick="alert('hi');">
<tr id="tbl1">
<td id="c1">one</td>
</tr>
<tr>
<td id="c2">two</td>
</tr>
</table> </body>
</html>

  

Example 7: Displaying Event Object Properties

This example uses DOM methods to display all the properties of the window.onload eventobject and their values in a table. It also shows a useful technique of using a for..in loop to iterate over the properties of an object to get their values.

The properties of event objects differs greatly between browsers, the WHATWG DOM Standardlists the standard properties, however many browsers have extended these greatly.

Put the following code into a blank text file and load it into a variety of browsers, you'll be surprised at the different number and names of properties. You might also like to add some elements in the page and call this function from different event handlers.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Show Event properties</title> <style>
table { border-collapse: collapse; }
thead { font-weight: bold; }
td { padding: 2px 10px 2px 10px; } .odd { background-color: #efdfef; }
.even { background-color: #ffffff; }
</style> <script> function showEventProperties(e) {
function addCell(row, text) {
var cell = row.insertCell(-1);
cell.appendChild(document.createTextNode(text));
} var e = e || window.event;
document.getElementById('eventType').innerHTML = e.type; var table = document.createElement('table');
var thead = table.createTHead();
var row = thead.insertRow(-1);
var lableList = ['#', 'Property', 'Value'];
var len = lableList.length; for (var i=0; i<len; i++) {
addCell(row, lableList[i]);
} var tbody = document.createElement('tbody');
table.appendChild(tbody); for (var p in e) {
row = tbody.insertRow(-1);
row.className = (row.rowIndex % 2)? 'odd':'even';
addCell(row, row.rowIndex);
addCell(row, p);
addCell(row, e[p]);
} document.body.appendChild(table);
} window.onload = function(event){
showEventProperties(event);
}
</script>
</head> <body>
<h1>Properties of the DOM <span id="eventType"></span> Event Object</h1>
</body> </html>

  

CSS Object Model (CSSOM)

The CSS Object Model is a set of APIs allowing the manipulation of CSS from JavaScript. It is much like the DOM, but for the CSS rather than the HTML. It allows users to read and modify CSS style dynamically.

CSS Typed Object Model

Obsolete CSSOM interfaces

Tutorials

Browser compatibility

All these features have been added little by little over the years to the different browsers: it was a quite complex process that can't be summarized in a simple table. Please refer to the specific interfaces for its availability.

UI——DOM的更多相关文章

  1. 【shadow dom入UI】web components思想如何应用于实际项目

    回顾 经过昨天的优化处理([前端优化之拆分CSS]前端三剑客的分分合合),我们在UI一块做了几个关键动作: ① CSS入UI ② CSS作为组件的一个节点而存在,并且会被“格式化”,即选择器带id前缀 ...

  2. ReactJS虚拟DOM效应带来的一则副作用探索

    疑问 https://github.com/ruanyf/react-demos/blob/master/demo08/index.html 在如下代码中的 18 行, 需要将本类中的 方法,进行绑定 ...

  3. JavaScript单线程和浏览器事件循环简述

    JavaScript单线程 在上篇博客<Promise的前世今生和妙用技巧>的开篇中,我们曾简述了JavaScript的单线程机制和浏览器的事件模型.应很多网友的回复,在这篇文章中将继续展 ...

  4. 【前端优化之拆分CSS】前端三剑客的分分合合

    几年前,我们这样写前端代码: <div id="el" style="......" onclick="......">测试&l ...

  5. 浅谈js命名空间管理

    在C# 和 Java里面我们如果想使用哪一个功能类就要引用相应的命名空间. 如C#里面有个System.Web.UI库,我们就要用using   System.Web.UI;,之后我们就可以用到Scr ...

  6. [Node.js] 基于Socket.IO 的私聊

    原文地址:http://www.moye.me/2015/01/02/node_socket-io/ 引子 最近听到这么一个问题:Socket.IO 怎么实现私聊?换个提法:怎么定位到人(端),或者说 ...

  7. Durandal介绍

         Durandal是一个JS框架用于构建客户端single page application(SPAs).它支持MVC,MVP与MVVM前端构架模式.使用RequireJS做为其基本约定层,D ...

  8. cocos2D(三)---- 第一cocos2d的程序代码分析

    在第一讲中已经新建了第一个cocos2d程序,执行效果例如以下: 在这讲中我们来分析下里面的代码,了解cocos2d的工作原理,看看屏幕上的这个"Hello World"是怎样显示 ...

  9. react programming

    So you're curious in learning this new thing called Reactive Programming, particularly its variant c ...

随机推荐

  1. 使用LPCXpresso开发板调试外部的电路板

    MCUXpresso IDE开发环境有一个主要的功能:支持LPC-Link2仿真调试器.通过这种方式,对于基于ARM的电路板,我可以使用这个功能强大的仿真调试器来调试.在NXP的众多LPCXpress ...

  2. burp插件debug

    java -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005 -jar burpsuite_community_v2. ...

  3. 微服务学习及.net core入门教程

    https://www.cnblogs.com/jackyfei/p/12067708.html https://www.cnblogs.com/jesse2013/ http://video.jes ...

  4. 带有EXE参数的启动

    (一).先制作一个带启动参数的EXE文件. 步骤:            1.定义全局私有变量:private string[] s = new string[1];  //这里为了简单起见,只做一个 ...

  5. 多任务创建-线程(IO密集型适用)

    单核CPU:时间片轮转 并行:CPU的个数大于等于任务数 真的多任务执行 并发:CPU的个数小于任务数 假的多任务 知识点: 多线程共享全局变量 创建线程的两种方法: 1.创建子线程方法 调用函数 T ...

  6. Vue之nextTick()

    我们有时候操作 DOM,是想在 data 数据变更的时候进行操作. 那么,我们应该怎么做呢? index.html <!DOCTYPE html> <html lang=" ...

  7. 随便写一个c++类

    为了让代码更贴合实际项目需要,我们分别用xxx.h文件,xxx.cpp文件来包含类的定义,类的声明和类的调用部分,实验平台vs2010 mycoach.h文件 #pragma once #includ ...

  8. Educational Codeforces Round 68

    目录 Contest Info Solutions A.Remove a Progression B.Yet Another Crosses Problem C.From S To T D.1-2-K ...

  9. 在其他博客里看到的比较好的map用法,进行储存啦啦~ x

    1.map简介 map是一类关联式容器.它的特点是增加和删除节点对迭代器的影响很小,除了那个操作节点,对其他的节点都没有什么影响.对于迭代器来说,可以修改实值,而不能修改key. 2.map的功能 自 ...

  10. js的老生代垃圾回收

    推荐阅读:<JS 闯关记>之垃圾回收和内存管理 常见的垃圾回收有2种策略:标记清除 和 引用计数 标记清除 会遍历堆中所有的对象,然后标记活的对象,在标记完成后,销毁所有没有被标记的对象. ...