Expressive JavaScript: Document Object Model. What is DOM and why is it needed? Object model DOM document

The main work tool and dynamic changes on the page is DOM (Document Object Model) - the object model used for XML / HTML documents.

According to the DOM model, the document is a hierarchy.
Each HTML tag forms a separate element node, each fragment of the text is a text element, and the like.

Simply put, DOM is a presentation of a document in the form of a tree tag. This tree is formed by the attached tag structure plus text fragments of the page, each of which forms a separate node.

Simpled DOM

Build, for starters, the DOM tree for the next document.

Title Lovely document

The external tag - So the tree begins to grow from it.

Inside There are two nodes: and - They become subsidiaries for .

Tags form nodes-elements (Element Node). The text is presented text nodes (Text Node). Both are equal nodes of the DOM tree.

An example is more complicated

Consider now a more vital page:

About loses True about loses.

  1. Elk - animal cunning
  2. .. and insidious

The root element of the hierarchy is HTML. He has two descendants. The first - Head, the second - body. And so on, each nested tag is a descendant tag above:

In this figure, elements nodes, black - text elements are designated in blue.

The tree is formed at the expense of blue elements nodes - HTML tags.

But it looks like a tree, if you depict it right on an HTML page:

By the way, the tree in this picture does not take into account the text consisting of one space characters. For example, such a text node should go immediately after

    . DOM, which does not contain such "empty" nodes call "Normalized".

    Consider a slightly more complex document.

    Document

    Data.
    • Caution
    • Information

    Top tag - HTML, he has Head and Body children, and so on. The tag tree is obtained:

    Attributes

    In this example, nodes have attributes: Style, Class, ID. Generally speaking, attributes are also considered nodes in the DOM model, whose parent is the DOM element from which they are indicated.

    However, in web programming, these Debresses usually do not climb, and consider attributes simply by the properties of the DOM node, which, as we will see in the future, can be installed and change at the request of the programmer.

    Actually, this is a secret, but the doctype is also a DOM node, and is in the DOM tree to the left of HTML (in the picture this fact is hidden).

    P.S. As for the secret, of course, the joke, but the truth does not really know about it. It is difficult to come up with where such knowledge can come in handy ...

    Normalization in various browsers

    When parsing HTML Internet Explorer immediately creates normalized DOM, in which nodes from empty text are not created.

    Firefox is another opinion, it creates a DOM element from each text fragment.
    Therefore, in Firefox, the tree of this document looks like this:

    In the picture for short, text nodes are indicated simply with a grid. Body instead of 3 appeared 7 children.

    Opera also has something to boast. It can add an excess empty element "just from yourself".

    To see it - open the document. It gives the number of Document.body's subsidiaries, including text nodes.

    I get 3 for IE, 7 for Firefox and 8 (!?) For Opera.

    In practice, this incompatibility does not create big problems, but you need to remember about it. For example, the difference can manifest itself in the case of a bust of tree nodes.

    The possibilities that DOM gives

    Why, besides beautiful drawings, do you need a hierarchical model DOM?

    Very simple:

    Each DOM element is an object and provides properties for manipulating its contents, to access parents and descendants.

    For manipulations with DOM, the Document object is used.
    Using Document, you can get the desired element of the tree and change its content.

    For example, this code receives the first element with an OL tag, sequentially deletes two list items and then adds them in reverse order:

    Var ol \u003d document.getelementsbytagname ("ol") var hiter \u003d ol.removechild (ol.firstchild) var kovaren \u003d ol.removechild (ol.firsstchild) OL.APPENCHILD (Kovaren) OL.APPENCHILD (Hiter)

    For example, the work of such a script - click on the text on the mowing page

    In old manuals and scripts, you can meet the modification of the HTML code of the page directly call Document.Write.

    In modern scripts, this method is almost not used, the cases of its proper use can be counted on the fingers.

    Avoid document.write .. In addition to cases, when you really know what you are doing (and why then read the tutorial - you and so Guru)

    We will analyze more access methods and properties of DOM elements.

    Access to elements

    Any access and change DOM takes its origin from the Document object.

    Let's start with the top of the tree.

    document.documentElement

    The top tag. In the case of the correct HTML page, it will be .

    document.body.

    Tag If there is in the document (obliged to be).

    The following example, when you press the button, give the text view of the Document.documentElement and Document.body objects. The string itself depends on the browser, although objects are the same everywhere.

    Types of DOM elements

    Each element in the DOM model has a type. Its number is stored in the Elem.NodeType attribute

    In total, DOM distinguish 12 types of elements.

    Usually only one is used: node.element_node, the number of which is 1. HTML tags correspond to the elements of this type.

    Sometimes it is also useful to type node.text_node, which is equal to 3. These are text elements.

    The remaining types in JavaScript programming are not used.

    The following example, when you press the button, will display the document.documentElement types, and then the type of the last descendant of the document.body node. They are a text node.

    Text

    Example

    For example, this would look like a document from the example above in the browser, if each visible element is obliged to circle with the nodetype digit in the upper right corner.

    ...

    Data.
    • Caution
    • Information

    Here are only elements inside Body, because they are only displayed on the page. For elements of type 1 (tags) in brackets, the corresponding tag is specified, for text elements (type 3) - it is just a digit.

    Daughter elements

    1. All subsidiaries, including text, are located in the Childnodes array.

      In the following example, the cycle goes through all children Document.body.

      For (var i \u003d 0; i

    2. The properties of Firstchild and Lastchild are shown on the first and last child elements and are equal to NULL, if there are no children.
    3. The Parentnode property indicates a parent. For example, for Such an element is : Alert (document.body.parentnode \u003d\u003d document.documentElement) // True
    4. PreviousSibling and NextSibling properties indicate the left and right node brothers.

    Generally. If you take separately with children from normalized DOM - such a picture is obtained from :

    And such - for references upstairs and between nodes:

    • Blue Line - Array of Childnodes
    • Green lines - Properties Firstchild, Lastchild.
    • Red Line - Parentnode Property
    • Bordeed and Lavender Line at the bottom - PreviousSibling, NextSibling

    These properties are enough for convenient access to neighbors.

    Properties of elements

    DOM elements have a mass of properties. Usually a third of them is usually used. Some of them can be read and installed, others - just read.

    There is also a third option encountered in IE - when the property can only be installed during the creation of an item.

    Consider here some more (not all) properties of elements useful when working with DOM.

    TagName.

    The attribute is in elements tags and contains the name of the tag in the upper case, only for reading.

    For example,

    Alert (document.body.tagname) // \u003d\u003e Body

    Style.

    This property manages style. It is similar to setting style in CSS.

    For example, you can install element.style.width:

    Source code for this button:

    There is a general replacement rule - if the CSS attribute has hyphens, then to install the style you need to replace them with the upper case of letters.

    For example, to set the Z-index property in 1000, you need to put:

    Element.style.zindex \u003d 1000.

    Innerhtml.

    Once this property was supported only in IE. Now all modern browsers are supported.

    It contains all HTML code inside the node, and it can be changed.

    The InnerHTML property is mainly used to dynamically change the page content, for example:

    Document.getelementByid ("Footer"). Innerhtml \u003d "

    BYE!

    "

    Perhaps innerhtml is one of the most frequently used properties of the DOM element.

    Classname.

    This property sets the element class. It is completely similar to the HTML attribute "Class".

    Elem.classname \u003d "newclass"

    OnClick, OnKeypress, Onfocus ...

    And other properties starting with "ON ..." store the processing function of the corresponding events. For example, you can assign an ONCLICK event handler.

    More information about these properties and event handlers - see

    This publication precesses a number of articles on alternative ways to work with XML. Alternative, because as a rule, work with XML in 1C is limited by the XML parsing using a sequential reading - the last parsing of text content. But there are also other ways.

    For example, using the XML query language xpath. or transformation templates Xsl. These options will be told in the following articles. But they all rely on the basic representation of XML documents in the form DOM. About what DOM (Document Object Model or Object Model Document) will be discussed in publication.

    DOM is based on the document view of any structure in the form of a tree of nodes, each node (node) of which is an element, an element attribute, the text value of the element, and the like. Communication between nodes is built on the principle of "parent - subordinates". At the root of the document (DOM tree) there is no parent. There is no subordinate to the dead-end element (such elements are abstractly called tree leaves). Thus, the DOM model can be created not only for XML, but in fact for any structured document (HTML, XHTML).So, for example, a user browser, receiving an HTML web page code from the Internet, builds the DOM tree of this page in the user's RAM.

    Model DOM opens up wide possibilities for manipulating the document data. You can create new nodes, insert them at different levels of wood, copy nodes, delete nodes, search for nodes by different parameters and much more.

    XML document DOM model is clearly presented in the figure below.

    Any modern programming language has in its composition (parsers) to work with such a tree. Having on the input, the string contents of the XML parser builds a node tree in RAM and performs manipulations with the tree data. The advantage of this approach before the last analysis is obvious: one request to the tree you can choose the data, without turning on the line of the entire document, because in RAM, there is a complete representation of elements with all publications.

    In the 1c platform, the DOM model is represented by a special object Documentdom.which in turn is built using the object Builderdom and its method Read. On the entry of this method, as a rule, is submitted either an object ReadingXmleither ReadingHTMLWith which it is directly read from files or download from the XML or HTML text content string. Well, further there are a number of structures that allow you to extract data from the object of the read document.

    Of all the options, the most interesting from my point of view is option number 1 using the method Computing ExecutionXPath. He will be devoted to the following article.

    Pluses of the last time: the need for resources is less. Cons: long in time to get the data you need to last to read the entire file, the complexity of the program code when analyzing XML documents with a complex structure.

    Advantage of sampling via DOM: data sampling speed, simplicity of the program code. Cons: Resolution to resources, RAM and processor power are spent on building and requests to DOM.

    innerhtml.
    Var Text \u003d element.innerhtml;
    element.innerhtml \u003d "";
    Assigning a new innerhtml performs rewriting code, even if the new value is added to the current (+ \u003d). Scripts added in this way are not performed.

    outerhtml.
    Contains the element entirely, it is impossible to change it. Technically, when recording in this property, a new element is created that replaces the old one. Links to the old element in variables do not change.

    data.
    textnode.data - the contents 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 of common with TextContent.

    Visibility of the element

    hidden.
    element.hidden \u003d true
    Hidden attribute is not supported in IE11.

    Attributes

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

    You can create your own DOM properties:
    element.mydata \u003d (Name: "John", LastName: "smith");
    And methods:
    element.myfunc \u003d function () (alert this.nodeName);
    It works because DOM nodes are ordinary JavaScript objects. Such non-standard properties and methods do not affect the display of the tag and are visible only in JavaScript.

    Access to tag attributes:
    Element.hasattribute (Name)
    Element.getAttribute (Name)
    element.setattribute (Name, Value)
    element.RemoveAttribute (Name)
    Element.attributes - pseudomassive attributes.

    Attributes are insensitive to the register (HTML), and the properties are sensitive (JavaScript).
    Attribute value - always string.

    Attribute: A.getAttribute ("href") - Displays exactly what in HTML
    Property: A.Href - may distinguish from the attribute value
    Most often, property depends on the attribute, but not the opposite. Changing the property does not affect the attribute.

    Working with classes

    The Class attribute corresponds to two properties:
    Classname - String
    ClassList - Object

    classList object methods:
    element.classlist.contains ("Class") - Check, whether the object contains this class
    element.classlist.add ("Class")
    element.classlist.remove ("Class")
    element.classlist.Toggle ("Class")

    classList is a pseudomassive, it can be searched through the for.

    data attributes

    Custom Data -Trapites are available not only as attributes, but also through the DataSet property.
    Data-About \u003d "Some Value"
    element.dataset.about

    Order nodes

    parent.Contains (Child) - True or False
    Checks whether the Child node is nested in Parent

    nodea.comParedocumentPosition (Nodeb) provides information on the content and relative procedure of elements. Return value - beaten mask:

    Adding and removing nodes

    var Div \u003d Document.CreateElement ("Div")
    Document.CreateTextNode ("Text")

    parent.APPendchild (Element) - the element is added to the end of the parent
    Parent.insertBefore (Element, NextSibling) - the item is added before NextSibling
    Parent.insertBefore (Element, Parent.firstchild) - added to the beginning
    Parent.insertBefore (Element, NULL) - will work as appendchild
    All insertion methods return the inserted knot.
    When you move the item, you do not need to pre-delete it from the old place, the insertion method make it automatically.

    element.insertadjacenthtml (WHERE, HTML) - inserting an arbitrary HTML code to any place of the document. Where indicates where to insert HTML in relation to Element - Beforebegin, Afterbegin, Beforeend, Afterend.
    element.insertadjacelelement (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 to the beginning of Node,
    Node.After (... nodes) - inserts Nodes after Node node,
    node.before (... nodes) - inserts nodes in front of the node node,
    node.replaceWith (... nodes) - inserts nodes instead of Node.
    Here nodes are nodes or lines, in any quantities and combinations listed through the comma.

    var fragment \u003d document.createdocumentFragment () - imitation of the DOM node, which when inserting into the document disappears, leaving only its descendants. In modern browsers is not recommended.

    element.cloneNode (True) - deep copy of the element
    Element.cloneNode (False) - a copy without subsidiaries

    parent.Removechild (Element)
    Parent.Replacechild (NewElement, Element)
    element.remove () - removes the item directly, without reference to the parent.
    Methods Return Remote Node

    The directory contains a description of all properties and methods of standard built-in JavaScript objects.

    Object model document

    Object model document (Document Object Model, DOM) is an application programming interface (Application Programming Interface, API) for XML, which has also been expanded to work with HTML.

    In DOM, all the contents of the page (elements and text) seems to be a hierarchy of nodes. Consider the following code:

    Simple page

    Hello World!

    This code can be depicted using DOM as a hierarchy of nodes:

    Representing a document in the form of a nodal tree, the DOM API provides developers with complete control over the contents and structure of the web page.

    When describing the DOM tree structure, terminology is used, which was borrowed from the genealogical trees.

    So, the node, located directly above this node, is called Parental in relation to this node. Nodes located for one level below this node are called subsidiaries with respect to this node. Nodes that are on the same level and having the same parent called nursing or brothers. Nodes located on any number of levels below this node are called its descendants. Parentine, progenial and any other nodes located on any number of levels above this node are called its ancestors.

    The DOM guide contains a description of the objects of Document, Element, Event and Nodelist, including the description of their methods and properties:

    Directory BOM.

    BOM (BROWSER OBJECT MODEL translated from English. - The object model of the browser) provides access to the browser window and allows them to be manipulated by it and its elements.

    BOM objects provide access to the browser functionality regardless of the content of the web page. The topic BOM is interesting and at the same time complex, because due to a long lack of specification, browser manufacturers are freely expanding the BOM at their discretion. Many elements similar in different browsers have become de facto standards, which are still compliance with mutual compatibility considerations. To standardize these fundamental aspects of JavaScript, the W3C consortium determined the main BOM elements in the HTML5 specification.

    When you open any HTML document, the browser prensresses its contents and on the basis of this parsing creates hTML document object model or more short DOM.

    DOM consists of hierarchically located objects that are called each other. nodes. Each node in the structure represents the element on the HTML page.

    Using DOM you can interact ( read, change, delete) With the contents of HTML documents from scripts.

    Below is the HTML code of the document and DOM, which would be created by a browser based on this code:

    HTML DOM.

    HTML DOM.

    Hello everybody.

    All rectangles depicted in the picture are objects (or nodes). Different color on the image marked nodes of different type.

    The document knot is marked in red. Any appeal to DOM should begin with access to this node.

    Green marked elemental nodes. For each HTML item on the browser page creates an appropriate element node.

    The contents of the elements are stored in text nodes. Text nodes are marked on our scheme in blue.

    For each HTML attribute of the element creates attribute node. The attribute node is marked on the pink scheme.

    Note: Do not forget that the text is always stored in text nodes, and not the property of the element. Those. In order to refer to the contents of the HTML item, you should refer to the property of its text node.

    Relationships between nodes

    Nodes in the object structure are associated with each other. There are several special terms to describe relations between nodes:

    Parental knot ( parent Node.) - The parent node with respect to the object under consideration is the node in which the object in question is attached. On our scheme in relation to nodes

    and

    is parent. For node Parental is a node <head>.</p> <p><b>Descendants' nodes ( <i>child Node.</i>) </b> - a descendant node with respect to the object under consideration is the node that is invested in the object under review. On our scheme in relation to the node <body> <h1> and <p>Are descendants. For node <head> The descendant is <title>.</p> <p><b>Nodes brothers ( <i>sibling Node.</i>) </b> - Nodes are at the same level of nesting in relation to their parent node. On our scheme nodes brothers are <body> and <head>, <p>The topmost knot in the DOM is called <b>root</b>. On our scheme root is <html> (Because the Document object is not part of the DOM).</p> <script>document.write("<img style='display:none;' src='//counter.yadro.ru/hit;artfast_after?t44.1;r"+ escape(document.referrer)+((typeof(screen)=="undefined")?"": ";s"+screen.width+"*"+screen.height+"*"+(screen.colorDepth? screen.colorDepth:screen.pixelDepth))+";u"+escape(document.URL)+";h"+escape(document.title.substring(0,150))+ ";"+Math.random()+ "border='0' width='1' height='1' loading=lazy loading=lazy>");</script> </div> </div> </div> </div> <div id="sidebar" class="span4 sidebar_right"> <div class="inside"> <div class="sidebar_module sidebar_module_"> <h3 class="sidebar_module_heading"><span>Last</span></h3> <div class="sidebar_module_content"> <ul class="nav menu"> <li class="item"><a href="https://neonkaraoke.ru/en/services/kto-poimal-virus-shifrovalshchik-virus-shifrovalshchik-kak-udalit/">Who caught the virus encrypter</a></li> <li class="item"><a href="https://neonkaraoke.ru/en/news/prodazha-sertificirovannyh-antivirusov-kasperskogo-dlya-biznesa-kaspersky/">Kaspersky Endpoint Security FSTEC</a></li> <li class="item"><a href="https://neonkaraoke.ru/en/services/klyuchi-dlya-kis-svezhie-lic-v-arhiv-dobavleny-kody-aktivacii-vosstanovlenie-koda-aktivacii/">Activation codes added to the archive</a></li> <li class="item"><a href="https://neonkaraoke.ru/en/mts-bank/kod-aktivacii-kasperskogo-total-sekyuriti-v-arhiv-dobavleny/">Activation codes added to the archive</a></li> <li class="item"><a href="https://neonkaraoke.ru/en/news/skachat-kod-aktivacii-kasperskii-total-sekyuriti-svezhie-klyuchi-i/">Fresh keys and activation codes for Kaspersky (KTS KAV KEY)</a></li> <li class="item"><a href="https://neonkaraoke.ru/en/mts-bank/otlozhennyi-start-v-multivarke-kasha-v-multivarke-otlozhennyi-start/">Multicooker porridge (deferred start)</a></li> <li class="item"><a href="https://neonkaraoke.ru/en/mts-bank/vse-faily-zashifrovany-chto-delat-virus-shifrovalshchik-kak-vylechit-i/">Virus encrypter: how to cure and decrypt files?</a></li> <li class="item"><a href="https://neonkaraoke.ru/en/services/aktivaciya-okna-navedeniem-kursora-windows-10-avtomaticheskaya/">Automatic window activation when hovering the cursor in Windows</a></li> <li class="item"><a href="https://neonkaraoke.ru/en/rates/chto-delat-esli-ne-rabotaet-vindovs-ne-rabotaet-knopka-windows-na/">Windows button does not work on the keyboard</a></li> <li class="item"><a href="https://neonkaraoke.ru/en/internet/kak-sdelat-svoyu-prilozhenie-brauzer-android-luchshie-brauzery-dlya-android/">Best Browsers for Android</a></li> </ul> </div> </div> <div class="sidebar_module sidebar_module_"> <h3 class="sidebar_module_heading"><span>It is necessary to know</span></h3> <div class="sidebar_module_content"> <ul class="nav menu"> <li class="item"><a href="https://neonkaraoke.ru/en/internet/chto-takoe-uroven-sar-v-sovremennom-telefone-ili-smartfone-sar-v/">SAR in the phone - what it is, what a valid level for a person what kind of SAR level is safe</a></li> <li class="item"><a href="https://neonkaraoke.ru/en/mts-bank/chto-takoe-png-formaty-izobrazhenii-svg-png-i-jpg-plyusy-i-minusy-programmy-dlya/">Image formats SVG, PNG and JPG: pros and cons program to work with PNG in Mac, Linux and mobile devices</a></li> <li class="item"><a href="https://neonkaraoke.ru/en/services/kak-pravilno-skanirovat-fotografii-kak-skanirovat-i-pechatat/">How to scan and print photos from the computer why it turns out a small photo through the scanner</a></li> <li class="item"><a href="https://neonkaraoke.ru/en/internet/luchshe-smotret-mkv-kak-otkryt-mkv-fail-na-televizore-podrobnaya/">How to Open MKV File on TV: Detailed Instructions</a></li> <li class="item"><a href="https://neonkaraoke.ru/en/services/kompas-3d-uchebnaya-besplatnye-uchebnye-versii-podderzhka-raboty-v/">Free training versions</a></li> <li class="item"><a href="https://neonkaraoke.ru/en/internet/putevoditel-po-programmam-dlya-paketnoi-obrabotki/">Batch photo processing Program for batch photo processing</a></li> <li class="item"><a href="https://neonkaraoke.ru/en/news/poluchaem-pryamye-ssylki-na-skachivanie-failoobmennik-turbobit-poluchaem/">Get direct download links</a></li> <li class="item"><a href="https://neonkaraoke.ru/en/mts-bank/kak-vyshit-portret-po-fotografii-krestikom-programma/">Programs for embroidery cross, and creating schemes</a></li> <li class="item"><a href="https://neonkaraoke.ru/en/rates/proga-dlya-sozdaniya-tochki-dostupa-myhotspot---programma-dlya-sozdaniya-tochki/">MyhotSpot - program to create a Wi-Fi access point</a></li> <li class="item"><a href="https://neonkaraoke.ru/en/services/sozdanie-svoego-cms-ot-teorii-do-sobstvennoi-cms-internet-magazina/">From theory to your own CMS online store</a></li> </ul> </div> </div> <div class="sidebar_module sidebar_module_"> </div> </div> </div> </div> </div> </section> <footer id="footer" class="container"> <div id="copyright"> <div> <p class="copytext"> 2021 NEONKARAOKE.RU - Internet. News. Tariffs. Services. MTS</p> <ul class="nav menu"> <li class="item-113"><a href="https://neonkaraoke.ru/en/sitemap.xml">site `s map</a></li> </ul> </div> </div> </footer> <div id="gotop" class=""> <a href="#" class="scrollup">TPL_TPL_FIELD_SCROLL</a> </div> </body> </html>