Introduction. Working with the DOM Model What is the Document Object Model dom

In this lesson, we'll look at what the DOM is, why it's needed, and how it's built.

What is DOM?

The browser, when requesting a page and receiving its source HTML code in response from the server, must first parse it. In the process of parsing and parsing HTML code, the browser builds a DOM tree based on it.

After performing this action and a number of others, the browser proceeds to render the page. In this process, he is, of course, already using the DOM tree he created, not the original HTML.

DOM is the document object model that the browser creates in the computer's memory based on the HTML code it receives from the server.

To put it simply, HTML code is the text of a page, and DOM is a set of related objects created by the browser when parsing its text.

In Chrome, the source code of the page that the browser receives can be viewed in the "Source" tab in the "Web Developer Tools" panel.


In Chrome, there is no tool that can be used to view the DOM tree it has created. But there is a representation of this DOM tree in the form of HTML code, it is available on the "Elements" tab. This DOM representation is, of course, much more convenient for a web developer to work with. Therefore, there is no tool that would represent the DOM in the form of a tree structure.


Objects in this model are formed from almost everything that is in HTML (tags, text content, comments, etc.), including the document itself. Relationships between these objects in the model are formed based on how the HTML elements are located relative to each other in the code.

In this case, the DOM of the document after its formation can be changed. When the DOM changes, the browser redraws the page image almost instantly. As a result, our rendering of the page always conforms to the DOM .

To read and modify the DOM programmatically, the browser provides us with a DOM API or, in other words, a programming interface. In a simple way, the DOM API is a collection of a huge number of various objects, their properties and methods that we can use to read and modify the DOM .

To work with the DOM in most cases, JavaScript is used, because. to date, it is the only programming language in which scripts can be executed in a browser.

Why do we need a DOM API? We need it so that we can use JavaScript to change the page on the fly, i.e. make it dynamic and interactive.

The DOM API provides us (developers) with a huge number of methods with which we can change everything on the page, as well as interact with the user. Those. this programming interface allows us to create complex interfaces, forms, process user actions, add and remove various elements on the page, change their content, properties (attributes), and much more.

Now on the web there are practically no sites in the scripts of which there would be no work with the DOM.

What is the HTML code for a page?

Before proceeding to the study of the document object model, you must first remember what the source code of a web page (HTML document) is.

The source code of a web page consists of tags, attributes, comments, and text. Tags are the basic syntax of HTML. Most of them are in pairs. In this case, one of them is the opening one, and the other is the closing one. One such pair of tags forms an HTML element. HTML elements can have Extra options- attributes.

In a document to create a certain markup, some elements are inside others. As a result, an HTML document can be thought of as a set of nested HTML elements.

As an example, consider following html code:

Page Title Article Title Article Section

Article content

In this code, the root element is html . The head and body elements are nested within it. The head element contains the title , while the body element contains h1 and div . The div element in turn contains h2 and p .

Now let's look at how the browser builds a DOM tree based on the HTML code.

How is the document's DOM tree built?

As already described above, the browser builds a tree based on HTML elements and other entities. source code pages. When performing this process, it takes into account the nesting of elements within each other.

As a result, the browser uses the resulting DOM tree not only in its work, but also provides us with an API for convenient operation with it via JavaScript.

When building the DOM, the browser creates objects (nodes of the DOM tree) from HTML elements, text, comments, and other entities of this language.

In most cases, web developers are only interested in objects (nodes) formed from HTML elements.

At the same time, the browser does not just create objects from HTML elements, but also connects them with each other with certain connections, depending on how each of them relates to the other in the code.

Elements that are directly in an element are children of it. And he is a parent to each of them. In addition, all these elements in relation to each other are siblings (brothers).

Moreover, in HTML, any element always has one parent (the HTML element in which it is directly located). In HTML, an element cannot have multiple parents. The only exception is the html element. He doesn't have a parent.

To get the DOM tree as the browser builds it, you just need to "arrange" all the elements depending on their relationship to each other.

The creation of the DOM tree is done from top to bottom.

The root of the DOM tree is always the document itself (the document node). Further, the tree is built depending on the structure of the HTML code.

For example, the HTML code we looked at above would have the following DOM tree:


At the very top of this tree is the document node. This node is associated with html , it is its child. The html node is formed by the html(...) element. The head (...) and body (...) nodes have a parent relationship to html . In relation to each other, they are siblings, because have one parent. The head node is related to title (lt;title>...) and is its child. The h1 and div nodes are related to the body , for them it is the parent. The div node is related to h2(...) and p(), they are its children.

The tree starts, as noted above, from the object (node) document . It in turn has one child node formed by the html (...) element. The head(...) and body(...) elements are in html and therefore are its children. Next, the head node is the parent of title (lt;title>...). The h1 and div elements are nested within the body , which means they are its children. The div directly contains the h2(...) and p() elements. This means that the div node for each of them is the parent.

This is how the DOM tree is simply built in the browser based on the HTML code.

Why do you need to know how a DOM tree is built? First, it is an understanding of the environment in which you want to change something. Secondly, most of the actions when working with the DOM come down to finding (selecting) the necessary elements. Not knowing how the DOM tree is arranged and the connections between the nodes, find some certain element it will be quite difficult.

Exercise

Based on the DOM tree shown in the figure, create the HTML code.


Working with the DOM Model

Every Window object has a document property that refers to a Document object. This Document object is not a standalone object. It is the central object of a rich API known as the Document Object Model (DOM), which defines how the content of a document is accessed.

Overview of the DOM

The Document Object Model (DOM) is a fundamental application programming interface that provides the ability to work with the content of HTML and XML documents. The DOM Application Programming Interface (API) is not particularly complex, but there are many architectural features that you should be aware of.

First of all, it should be understood that nested HTML elements or XML documents are represented as a tree of DOM objects. The tree view of an HTML document contains nodes representing elements or tags such as and

And nodes representing lines of text. An HTML document can also contain nodes representing HTML comments. Consider the following simple HTML document:

Sample document This is an HTML document

Example simple text.

The DOM representation of this document is shown in the following diagram:

For those who are not yet familiar with tree structures in computer programming, it is helpful to know that the terminology to describe them has been borrowed from family trees. The node immediately above the given node is called parental with respect to this node. Nodes that are one level below another node are subsidiaries with respect to this node. Nodes that are at the same level and have the same parent are called sisterly. Nodes located any number of levels below another node are its children. Parent, grandparent and any other nodes above this node are its ancestors.

Each rectangle in this diagram is a document node, which is represented by a Node object. Note that the figure shows three different types of knots. The root of the tree is the Document node, which represents the entire document. The nodes that represent HTML elements are nodes of type Element, and the nodes that represent text are nodes of type Text. Document, Element and Text are subclasses of the Node class. Document and Element are the two most important classes in the DOM.

The Node type and its subtypes form the type hierarchy shown in the diagram below. Note the formal differences between the generic Document and Element types, and the HTMLDocument and HTMLElement types. The Document type represents an HTML and XML document, and the Element class represents an element of that document. The subclasses HTMLDocument and HTMLElement represent specifically an HTML document and its elements:

In this diagram, it should also be noted that a large number subtypes of the HTMLElement class that represent concrete types of HTML elements. Each of these defines JavaScript properties that reflect the HTML attributes of a particular element or group of elements. Some of these specific classes define additional properties or methods that do not reflect the syntax of the HTML markup language.

Selecting Document Elements

Majority work client programs in JavaScript is somehow related to the manipulation of document elements. During execution, these programs can use the document global variable, which refers to the Document object. However, in order to perform any manipulation on the elements of the document, the program must somehow obtain, or select, the Element objects that refer to those elements of the document. The DOM defines several ways to select elements. You can select an element or elements of a document:

    by the value of the id attribute;

    by the value of the name attribute;

    by tag name;

    by the name of the CSS class or classes;

    to match a specific CSS selector.

All of these element selection techniques are described in the following subsections.

Selecting elements by id attribute value

All HTML elements have id attributes. The value of this attribute must be unique within the document - no two elements in the same document must have the same id attribute value. Select item by unique value id attribute can be done using the getElementById() method of the Document object:

Var section1 = document.getElementById("section1");

This is the easiest and most common way to select elements. If the script needs to be able to manipulate a specific set of document elements, assign values ​​to the id attributes of those elements and use the ability to search them by those values.

Versions Internet Explorer below IE8, the getElementById() method searches for id attribute values ​​in a case-insensitive manner and also returns elements that match the value of the name attribute.

Selecting elements by the value of the name attribute

The HTML name attribute was originally intended for naming form elements, and the value of this attribute was used when the form data was submitted to the server. Like the id attribute, the name attribute assigns a name to an element. However, unlike id, the value of the name attribute does not have to be unique: multiple elements can have the same name at once, which is quite common when used in radio buttons and checkbox forms. Also, unlike id, the name attribute is only allowed on certain HTML elements, including forms, form elements, and elements and .

You can select HTML elements based on the values ​​of their name attributes using the getElementsByName() method of the Document object:

Var radiobuttons = document.getElementsByName("favorite_color");

The getElementsByName() method is not defined by the Document class, but by the HTMLDocument class, so it is only available in HTML documents and not available in XML documents. It returns a NodeList object that behaves like a read-only array of Element objects.

In IE, the getElementsByName() method also returns elements whose id attribute values ​​match the specified value. To ensure compatibility with different versions browsers, you need to be careful about choosing attribute values ​​and not use the same strings for name and id attribute values.

Selecting elements by type

The getElementsByTagName() method of the Document object allows you to select all HTML or XML elements of the specified type (or by tag name). For example, to get a read-only array-like object containing the Element objects of all the elements in the document, you can do the following:

var spans = document.getElementsByTagName("span");

Like the getElementsByName() method, getElementsByTagName() returns a NodeList object. Document elements are included in the NodeList array in the same order as they appear in the document, i.e. first element

In a document, you can choose:

Var firstParagraph = document.getElementsByTagName("p");

HTML tag names are case-insensitive, and when getElementsByTagName() is applied to an HTML document, it compares against the tag name in a case-insensitive manner. The spans variable created above, for example, will also include all elements that are written as .

You can get a NodeList containing all the elements in a document by passing the wildcard "*" to the getElementsByTagName() method.

In addition, the Element class also defines the getElementsByTagName() method. It acts exactly like the version of the method in the Document class, but only selects elements that are children of the element on which the method is called. That is, find all elements inside the first element

It is possible as follows:

Var firstParagraph = document.getElementsByTagName("p"); var firstParagraphSpans = firstParagraph.getElementsByTagName("span");

For historical reasons, the HTMLDocument class defines special properties for accessing certain types of nodes. Properties images, forms And links, for example, refer to objects that behave like read-only arrays containing elements , And (but only those tags , which have an href attribute). These properties refer to HTMLCollection objects, which are much like NodeList objects, but can additionally be indexed by the values ​​of the id and name attributes.

The HTMLDocument object also defines embeds and plugins synonymous properties, which are collections of HTMLCollection elements. The anchors property is non-standard, but it can be used to access elements A that has a name attribute but no href attribute. The scripts property is defined by the HTML5 standard and is a collection of HTMLCollection elements.

In addition, the HTMLDocument object defines two properties, each of which refers not to a collection, but to a single element. The document.body property represents an HTML document element, and the document.head property represents the . These properties are always defined in the document: even if there are no and elements in the original document, the browser will implicitly create them. The documentElement property of the Document object refers to the root element of the document. In HTML documents, it always represents the .

Selecting elements by CSS class

The value of the HTML class attribute is a list of zero or more identifiers separated by spaces. It makes it possible to define sets of related document elements: any elements that have the same identifier in the class attribute are part of the same set. The word class is reserved in JavaScript, so client-side JavaScript uses the className property to store the value of the HTML class attribute.

Typically, the class attribute is used in conjunction with CSS cascading style sheets to apply a common display style to all members of a set. However, in addition, the HTML5 standard defines the getElementsByClassName() method, which allows you to select sets of document elements based on the identifiers in their class attributes.

Like the getElementsByTagName() method, the getElementsByClassName() method can be called on both HTML documents and HTML elements, and returns a "live" NodeList object containing all document or element descendants that match the search criteria.

The getElementsByClassName() method takes a single string argument, but the string itself can contain multiple identifiers separated by spaces. All elements whose class attributes contain all of the specified identifiers will be considered matched. The order of the identifiers does not matter. Note that in both the class attribute and the getElementsByClassName() method argument, the class identifiers are separated by spaces, not commas.

The following are some examples of using the getElementsByClassName() method:

// Find all elements with class "warning" var warnings = document.getElementsByClassName("warning"); // Find all descendants of element with id "log" // with classes "error" and "fatal" var log = document.getElementById("log"); var fatal = log.getElementsByClassName("fatal error");

Selecting elements using CSS selectors

CSS Cascading Style Sheets have very powerful syntactic constructs known as selectors that allow you to describe elements or sets of elements in a document. Along with standardizing CSS3 selectors, another W3C standard known as the Selectors API defines JavaScript methods to get elements that match the specified selector.

The key to this API is the querySelectorAll() method of the Document object. It takes a single string argument with a CSS selector and returns a NodeList object representing all elements in the document that match the selector.

In addition to the querySelectorAll() method, the document object also defines a querySelector() method similar to the querySelectorAll() method, except that it returns only the first (in document order) matching element, or null if there are no matching elements.

These two methods are also defined by the Elements class. When they are called on an element, the entire document is searched for a match against the given selector, and then the result is filtered so that only the descendants of the used element remain. This approach may seem counterintuitive, as it means that the selector string can include the ancestors of the element being matched.

Document Structure and Document Navigation

After selecting a document element, it is sometimes necessary to find structurally related parts of the document (parent, siblings, child element). The Document object can be thought of as a tree of Node objects. The Node type defines properties that allow you to navigate through such a tree. There is another application interface for navigating through the document, as a tree of Element objects.

Documents as Node Trees

The Document object, its Element objects, and the Text objects that represent the text chunks in the document are all Node objects. The Node class defines the following important properties:

parentNode

The parent node of this node, or null for nodes that have no parent, such as Document.

childNodes

A readable array-like object (NodeList) that provides a representation of child nodes.

firstChild, lastChild

The first and last child nodes, or null if the given node has no children.

nextSibling, previousSibling

The next and previous sibling nodes. Brother nodes are two nodes that have the same parent. Their order corresponds to the order in the document. These properties link nodes in a doubly linked list.

nodeType

The type of this node. Nodes of type Document have a value of 9 in this property. Nodes of type Element - value 1. Text nodes of type Text - value 3. Nodes of type Comments - value 8 and nodes of type DocumentFragment - value 11.

nodeValue

The text content of the Text and Comment nodes.

nodeName

The tag name of an Element in which all characters are converted to uppercase.

With these properties of the Node class, you can refer to the second child node of the first child node of the Document object, as shown below:

Document.childNodes.childNodes == document.firstChild.firstChild.nextSibling

Let's say the document in question looks like this:

Test Hello World!

Then the second child node of the first child node will be the element . It contains the value 1 in the nodeType property and the value "BODY" in the nodeName property.

However, note that this API is extremely sensitive to changes in the text of the document. For example, if you add a single newline between the and tags in this document, that newline character will become the first child node (Text node) of the first child node, and the second child node will be the element, not the .

Documents as Element Trees

When the document elements themselves are of primary interest, rather than the text within them (and the whitespace between them), it is much more convenient to use an API that allows you to interpret the document as a tree of Element objects, ignoring the Text and Comment nodes that are also part of the document.

The first part of this API is the children property of Element objects. Like the childNodes property, its value is a NodeList object. However, unlike the childNodes property, the children list contains only Element objects.

Note that the Text and Comment nodes do not have child nodes. This means that the Node.parentNode property described above never returns Text or Comment nodes. The value of the parentNode property of any Element object will always be another Element object or the root of the tree, a Document or DocumentFragment object.

The second part of the document element navigation API is the properties of the Element object, similar to the properties of accessing the child and sibling nodes of the Node object:

firstElementChild, lastElementChild

Similar to the firstChild and lastChild properties, but return child elements.

nextElementSibling, previousElementSibling

Similar to the nextSibling and previousSibling properties, but return sibling elements.

childElementCount

Quantity child elements. Returns the same value as the children.length property.

These child and sibling access properties are standardized and implemented in all current browsers except IE.

innerHTML
vartext = element.innerHTML;
element.innerHTML = "";
Assigning a new innerHTML overwrites the code, even if the new value is added to the current one (+=). Scripts added this way are not executed.

outerHTML
Contains the entire element and cannot be modified. Technically, writing to this property creates a new element that replaces the old one. References to the old element in variables do not change.

data
textNode.data - content of text nodes and comments

textContent
element.textContent - text inside the element without tags.
There is also a non-standard innerText property that has a lot in common with textContent .

Element Visibility

hidden
element.hidden = true
The hidden attribute is not supported in IE11.

Attributes

Most standard attributes in the DOM become properties of the object:
element.id = "id"
For non-standard attributes, no property is created (undefined)

You can create your own DOM properties:
element.myData = (name:"John", lastName:"Smith");
and methods:
element.myFunc = function()(alert this.nodeName);
This works because DOM nodes are regular JavaScript objects. These non-standard properties and methods do not affect the display of the tag and are only visible in JavaScript.

Accessing tag attributes:
element.hasAttribute(name)
element.getAttribute(name)
element.setAttribute(name, value)
element.removeAttribute(name)
element.attributes is a pseudo array of attributes.

Attributes are case insensitive (html) and properties are case sensitive (javaScript).
The attribute value is always a string.

Attribute: a.getAttribute("href") - displays exactly what is in the HTML
Property: a.href - may differ from attribute value
Most often, a property depends on an attribute, but not vice versa. Changing the property does not affect the attribute.

Working with classes

The class attribute has two properties:
className - string
classList - object

classList object methods:
element.classList.contains("class") - check if an object contains a given class
element.classList.add("class")
element.classList.remove("class")
element.classList.toggle("class")

classList is a pseudo-array, it can be iterated through a for loop.

data attributes

Custom data attributes are available not only as attributes, but also through the dataset property
data-about = "some value"
element.dataset.about

Node order

parent.contains(child) - true or false
checks if child node is nested in parent

nodeA.compareDocumentPosition(nodeB) - Provides information about the content and relative order of elements. The return value is a bit mask:

Adding and Removing Nodes

vardiv = document.createElement("div")
document.createTextNode("text")

parent.appendChild(element) - the element is added to the end of the parent
parent.insertBefore(element, nextSibling) - element is added before nextSibling
parent.insertBefore(element, parent.firstChild) - added to the beginning
parent.insertBefore(element, null) - works like appendChild
All insert methods return the inserted node.
When moving an element, you do not need to first remove it from the old place, the insertion methods do this automatically.

element.insertAdjacentHTML(where, html) - insert arbitrary HTML code anywhere in the document. Where specifies where to insert html in relation to element - beforeBegin, afterBegin, beforeEnd, afterEnd.
element.insertAdjacentElement(where, newElement)
element.insertAdjacentText(where, text)
the last two methods are not supported in Firefox

node.append(...nodes) - inserts nodes at the end of node ,
node.prepend(...nodes) - inserts nodes at the beginning of node ,
node.after(...nodes) - inserts nodes after the node ,
node.before(...nodes) - inserts nodes before node ,
node.replaceWith(...nodes) - Inserts nodes instead of node .
here nodes are nodes or strings, in any number and combination, separated by commas.

var fragment = document.createDocumentFragment() - simulates a DOM node that disappears when inserted into a document, leaving only its children. IN modern browsers Not recommended.

element.cloneNode(true) - deep copy of the element
element.cloneNode(false) - copy without children

parent.removeChild(element)
parent.replaceChild(newElement, element)
element.remove() - removes the element directly, without reference to the parent.
Methods return the remote host

W3C
DOM creators

Before you start learning DOM technology, you should already know the basics HTML languages, CSS and , besides that, you need to read articles about HTML forms (know how to create buttons, text fields, etc.).

DOM (document object model) Document Object Model created by the World Wide Web Consortium (W3C).

DOM is a web technology that allows you to manipulate the HTML tags of a page through the JavaScript language. The DOM represents HTML tags as objects with properties and methods. Each HTML tag (object) on an HTML page, thanks to the DOM, has its own unique address. By accessing this address, JavaScript can manipulate the HTML tag.

Addresses in the DOM are generated automatically, but they are too long and complex. Therefore, the creators of the DOM made it possible for web programmers to write short addresses themselves, through the id (unique identifier) ​​selector.

How the DOM Works

The browser, when opening an HTML page, creates a DOM structure based on its tags, where each HTML tag appears as an object with its own unique address. The DOM structure is also called DOM tree, this tree consists of nodes which are HTML tags, attributes, text.

History of the DOM

Initially, the DOM was not standardized and the two existing at that time Netscape browser Navigator and Internet Explorer created the DOM on their own. At the time, web programmers had to learn two versions of the DOM.

On this moment, W3C has standardized the DOM and all browsers try to adhere to this standard.

This section provides a brief introduction to the Document Object Model (DOM) - what the DOM is, how HTML and XML document structures are provided, and how to interact with them. This section contains background information and examples.

What is the Document Object Model (DOM)?

The Document Object Model (DOM) is a programming interface (API) for HTML and XML documents. The DOM provides a structured representation of a document and defines how that structure can be accessed from programs that can change the document's content, style, and structure. A DOM representation consists of a structured group of nodes and objects that have properties and methods. Essentially, the DOM connects a web page to scripting languages ​​or programming languages.

A web page is a document. The document can be presented both in the browser window and in the HTML code itself. Either way, it's the same document. The DOM provides another way to represent, store, and manage this document. The DOM fully supports the object-oriented representation of a web page, making it possible to change it using a scripting language like JavaScript.

How is the DOM accessible?

You don't have to do anything special to work with the DOM. Various browsers have different DOM implementations, these implementations show varying degrees of compliance with the actual DOM standard (this is a topic we have tried not to cover in this documentation), but each browser uses its own DOM to make web pages accessible to scripting languages.

When you create a script using the element, or include an instruction in a web page to load the script, you can immediately start using the API using the elements either to interact with the document itself or to get the descendants of this document, i.e. various elements On the page. Your DOM programming can be as simple as displaying a message using an object function, or using more complex DOM methods that create new content, as shown in the following example:

In the following example, JavaScript code is defined inside an element, given code sets the function when the document is loaded (when the entire DOM is available for use). This function creates a new H1 element, adds text to that element, and then adds the H1 to the document tree:

< html > < head > < script >// run this function when the document is loaded window. onload = function () ( // create multiple elements // in an empty HTML page header = document. createElement( "h1" ) ; heading_text = document. createTextNode( "Big Head!" ) ; heading. appendChild(heading_text); document. body. appendChild(heading); )< body >Important Data Types

This section is intended to briefly describe various types and objects in a simple and accessible manner. There are a number of different data types that are used in the API that you should be aware of. For simplicity, the syntax of the examples in this section typically refers to nodes as element s, node arrays as nodeList s (or just element s), and node attributes as simply attribute s.

Below is a table with brief description these data types.

document When a member returns an object of type document (for example, the element's ownerDocument property returns the document to which it belongs), that document object is its own root object. The DOM document Reference section describes the document object.
element
element denotes an element or node of type element returned by a member of the DOM API. Instead of saying that the document.createElement() method returns a reference to a node, we'll just say that this element returns an element that was just created in the DOM. element objects implement the DOM element interface and also the more general Node interface. Both interfaces are included in this help.
nodeList
NodeList

an array of elements, like the one returned by the Document.getElementsByTagName() method. Specific elements in an array are accessed by index in two ways:

  • list.item(1)

These methods are equivalent. In the first way, item() is the only method of the NodeList object. The latter uses the normal array syntax to get the second value in the list.

attributes When attribute is returned by an API member (for example, the createAttribute() method), it will be a reference to an object that provides a special (albeit small) interface for attributes. Attributes are nodes in the DOM, just like elements, although you may rarely use them as such.
namedNodeMap namedNodeMap is like an array, but the elements are accessible by name or index. Access by index is just for enumeration convenience. the elements have no particular order in the list. This datatype has an item() method for this purpose and you can also add and remove items from namedNodeMap
DOM interfaces

This guide is about objects and real things that you can use to manage the DOM hierarchy. There are many points where understanding how it works can be surprising. For example, an object representing an HTML form element takes its name property from the HTMLFormElement interface and its className property from the HTMLElement interface. In both cases, the property you want is on that form object.

Also, the relationship between objects and the interfaces they implement in the DOM can be surprising, and this section tries to talk a little about the interfaces that exist in the DOM and how they can be accessed.

Interfaces and objects

Many objects implement actions from multiple interfaces. The table object, for example, implements a special that includes methods such as createCaption and insertRow . But since it's a table, it's also an HTML element, table implements the Element interface described in section . Finally, since an HTML element (in the DOM sense) is a node in the tree that makes up the object model for an HTML or XML page, a table element also implements the more general Node interface from which Element derives.

vartable = 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 several of the most common interfaces in the DOM. The idea is not to describe what these API methods do, but to give you a few thoughts on the kinds of methods and properties that you will often see using the DOM. These common parts of the API are used in most of the examples in the section at the end of this help.

Document, window are objects whose interfaces you tend to use a lot in DOM programming. talking in simple words, the window object represents something like a browser, and the document object represents the root of the document itself. Element inherits from the common interface Node , and these interfaces together provide many methods and properties that can be used on individual elements. These elements can also have separate interfaces for working with the data types that these elements contain, as in the table object example in the previous case.

Below is short list common members of the API used in programming web and XML pages using the DOM:

  • parentNode.appendChild(node)
DOM API testing

This document contains examples for each interface that you can use in your development. In some cases, the examples are full web pages with access to the DOM in the element, the elements needed to run the script on the form, and the HTML elements that DOM operations will be performed on are also listed. When this happens, you can simply copy and paste the example into a new HTML document, save it, and run it in your browser.

There are cases, however, where the examples are more concise. To run the examples, which only demonstrate the basics of how interfaces interact with HTML elements, you can prepare a test page where you put functions inside scripts. The following very simple web page contains an element in the header where you can put functions to test the interface. The page contains several elements with attributes that can be returned, set or, in other words, manipulated and contains user interface needed to call desired functions from browser.

You can use this test page or a similar one to test the DOM interfaces you are interested in and see how they work in browsers. You can update the contents of the test() function as needed, create more buttons, or add elements as needed.

< html > < head > < title >DOM Tests< script type = " application/javascript" >function setBodyAttr (attr, value) ( ​​if (document. body) eval ("document. body." + attr+ "="" + value+ """ ) ; else notSupported () ; )< body > < div style =" margin : .5 in; height : 400 ; " > < p > < b > < tt >text< form > < select onChange = " setBodyAttr(" text" , this.options.value);" > < option value = "black" >black< option value = "dark blue" >dark blue< p > < b > < tt >bgColor< select onChange = " setBodyAttr(" bgColor" , this.options.value);" > < option value = "white" >white< option value = "light gray" >gray< p > < b > < tt >link< select onChange = " setBodyAttr(" link" , this.options.value);" > < option value = "blue" >blue< option value = "green" >green< small > < a href = " http://www.brownhen.com/dom_api_top.html" id = " sample" >(sample link)< br > < form > < input type = " button" value = "version" onclick = " ver()" />

To test many interfaces on the same page, a set of properties that change the colors of a web page, you can create a similar web page with a whole "console" of buttons, text fields, and other elements. The following screenshot gives an idea of ​​how interfaces can be grouped together for testing.

In this example, the dropdown menu dynamically updates the DOM-accessible parts of the web page (for example, background color, link color, and text color). However, when developing test pages, testing interfaces, as you read about it, is an important part of learning. effective work with DOM.