Home > Web Front-end > JS Tutorial > Compare the differences and connections between BOM and DOM in Javascript

Compare the differences and connections between BOM and DOM in Javascript

巴扎黑
Release: 2017-08-09 11:18:14
Original
1370 people have browsed it

1.Javascript composition

The implementation of JavaScript includes the following 3 parts:

1) Core (ECMAScript): Describes the # of JS ##Syntax and basic objects.

2

) Document Object Model (DOM): Methods and interfaces for processing web page content

3

) Browser Object Model (BOM): Methods and interfaces for interacting with the browser

ECMAScriptExtended knowledge:

ECMAScript is a standard,JS is just an implementation of it, other implementations include ActionScript.

② "

ECMAScript can provide core script programming capabilities for different types of host environments...", that is, ECMAScript is not bound to a specific host environment. For example, the host environment of JS is the browser, and the host environment of AS is Flash.

ECMAScript describes the following: syntax, types, statements, keywords, reserved words, operators, objects.

We all know that

javascript consists of three parts, ECMAScript, DOM and BOM , depending on the host (browser), the specific form of expression is also different, ie and other browser styles are very different.

1. DOM

is the standard of W3C; [ is publicly followed by all browsers Standard ]2. BOM
is the implementation of each browser manufacturer on their respective browsers based on DOM
;[shows that different browsers have different definitions,implementation methods are different]3. window
is a BOM object, not a js object;

DOM (Document Object Model) is Application programming interfaces (APIs) for HTML and XML.

BOM mainly deals with browser windows and frames, but usually browser-specific JavaScript extensions are considered part of

BOM . These extensions include:

Pop up a new browser window

Move, close and resize the browser window

Provide

Web Location object for browser details

Screen object that provides detailed information about the user's screen resolution

Support for

cookies

IE 扩展了 BOM,加入了ActiveXObject类,可以通过JavaScript实例化ActiveX对象

javacsript是通过访问BOM(Browser Object Model)对象来访问、控制、修改客户端(浏览器),由于BOM的window包含了document,window对象的属性和方法是直接可以使用而且被感知的,因此可以直接使用window对象的document属性,通过document属性就可以访问、检索、修改XHTML文档内容与结构。因为document对象又是DOMDocument Object Model)模型的根节点。可以说,BOM包含了DOM(对象),浏览器提供出来给予访问的是BOM对象,从BOM对象再访问到DOM对象,从而js可以操作浏览器以及浏览器读取到的文档。其中
DOM包含:window

Window对象包含属性:documentlocationnavigatorscreenhistoryframes

Document根节点包含子节点:formslocationanchorsimageslinks

从window.document已然可以看出,DOM的最根本的对象是BOMwindow对象的子对象。

区别DOM描述了处理网页内容的方法和接口,BOM描述了与浏览器进行交互的方法和接口

 

 

1.1 DOM, DOCUMENT, BOM, WINDOW 区别

DOM 全称是 Document Object Model,也就是文档对象模型。是针对XML的基于树的API。描述了处理网页内容的方法和接口,是HTML和XML的API,DOM把整个页面规划成由节点层级构成的文档。针对XHTML和HTML的DOM。这个DOM定义了一个HTMLDocument和HTMLElement做为这种实现的基础,就是说为了能以编程的方法操作这个 HTML 的内容(比如添加某些元素、修改元素的内容、删除某些元素),我们把这个 HTML 看做一个对象树(DOM树),它本身和里面的所有东西比如

These tags are regarded as an object, and each object is called a node. The node can be understood as the parent class of all Objects in the DOM.

What is the use of DOM? It is to operate elements in HTML. For example, if we want to change the title of this web page through JS, just do this:

document.title = 'how to make love';

This API makes it possible to change the content of a web page after it has been downloaded to the browser.

document

When the browser downloads a web page, usually HTML, this HTML is called document (of course, this is also a node in the DOM tree), from As you can see from the above figure, document is usually the root node of the entire DOM tree. This document contains attributes such as title (document.title) and URL (document.URL), which can be accessed directly in JS.

There may be multiple documents in a browser window. For example, each page loaded through an iframe is a document.

In JS, you can access its child nodes through document (in fact, any node can be used), such as

document.body;document.getElementById('xxx');


BOM

BOM is the Browser Object Model, Compare the differences and connections between BOM and DOM in JavascriptBrowser Object Model.


I just said that DOM is an interface that appears to operate documents, so BOM, as the name suggests, is actually an interface that appears to control the behavior of the browser.

What can the browser do? For example, to jump to another page, go forward, back, etc., the program may also need to obtain parameters such as the size of the screen.

So BOM is the interface that appears to solve these things. For example, if we want the browser to jump to another page, we only need

location.href = "http://www.xxxx.com";


This location is the BOM an object in .

#window

window is also an object of the BOM. In addition to the "backup object" in the programming sense, this object can be used to obtain the window position, determine the window size, Pop up dialog boxes, etc. For example, if I want to close the current window:

window.close();



To summarize the question:

DOM is for The API is used to operate the document, and document is one of its objects;
BOM is the API that is used to operate the browser, and window is one of its objects.

Responsible for DOM:

E area (that’s what you said document. It’s developed by web developers with great effort A folder written out contains index.html, CSS and JSWhat the hell, it is deployed on the server. We can enter URL through the address bar of the browser and press Enter to copy this documentLoad to local, browse, right-click to view source code, etc.

Managed by BOM:

A area (browser tabs, address bar, search bar, bookmarks bar, window zoom restore close button, menu bar, etc.)

B area (right-click menu of the browser)

C area (document when loading Status bar, showing http status code, etc.)

D area (scroll barscroll bar

BOM is the browser object model, DOM is the Document Object Model, the former operates on the browser itself , and the latter is a schematic diagram of the structural relationship between

BOM and DOM that operates on the content in the browser (can be seen as a container)

2. Document Object Model (DOM)

DOMNode tree model (take HTML DOM tree as an example)

DOM model combines the entire document (XML document and HTML document) is viewed as a tree structure,

in DOM, HTML document The hierarchical structure is represented as a tree structure. And use the document object to represent the document , and each child node of the tree represents different content in the HTML document.

Every HTML document loaded into the browser will become a Document object , Document is the entrance to explore DOM,Use global variablesdocumentCan access DocumentObject

2.1 Get to know DOM

First look at the following code

Decompose the HTML code into a DOM node hierarchy diagram:

DOM represents documents by creating trees and describes methods and interfaces for processing web content, giving developers unprecedented control over the content and structure of documents. The DOM API can Remove, add and replace nodes easily.

1) Node type

DOM specifies that each component in the document is a node (Node,HTMLThe document can be said to be a collection of nodes,DOMThe nodes are:

1. Element node (Element): , < in the above picture ;body>,

, etc. are all element nodes, that is, labels.

2. Text node (Text):The content displayed to the user, For example, JavaScript, DOM## in

  • ...
  • #, CSS and other texts.

    3.

    Attribute node (Attr):Element attribute, only the element has Attribute , such as the link attribute href="http://www.baidu.com" of the tag.

    1) DOMThree major attributes of nodes (XML DOM)

    1) nodeName: Element node, attribute node, and text node return the name of the element, the name of the attribute, and #text## respectively. #String.

    2

    )nodeType: nodeType of element nodes, attribute nodes, and text nodes The values ​​are 1, 2, 3.,

    3

    )nodeValue: The return values ​​of element nodes, attribute nodes, and text nodes are null respectively. , attribute values ​​and text node contents.

    2.2 DOMCommon operations

    Node

    is the parent interface of all nodes, which defines a set of common attributes and methods, as follows:

    Compare the differences and connections between BOM and DOM in Javascript1) Get the node

    ① Get the element node: through

    documentThree methods to obtain the object

    document.getElementById("ID")

    document.getElementByName("name")

    document.getElementsByTagName("p");

    ② Get the attribute node: The attribute node is attached to the element node. You can get the attribute node through the

    getAttributeNode(attrName) method of the element node, or you can Obtain the attribute value directly through getAttribute(attrName). (In contrast, Element interface’s setAttribute(attrName , attrValue) method, if the attribute does not exist, it is added directly to the element node)

    ③ Get the text node: The text node is a child node of the element node, and can be passed through the element Obtained by the

    childnodes()[index] method provided by the node (Element interface).

    childNodes //NodeList, a list of all child nodes

    firstChild //Node, pointing to the first node in the childNodes list

    lastChild //Node , points to the last node in the childNodes list

    parentNode //Node, points to the parent node

    previousSibling /Node, / points to the previous sibling node: if this node is the first node, Then the value is null

    nextSibling //Node, pointing to the next sibling node: if this node is the last node, then the value is null

    hasChildNodes()` //Boolean, when When childNodes contains one or more nodes, return true value

    Compare the differences and connections between BOM and DOM in Javascript2 Change the node

    ① Change the value of the attribute node: You can directly modify the attribute value through the

    nodeValue of the attribute node, or you can also use the of the element node The setAttribute() method changes.

    ② Change the value of the text node: modify it directly through the

    nodeValue of the text node.

    In the

    HTML DOM, the easiest way to get and change the content of an element is to use the element's innerHTML attribute ( innerTextThe property returns innerHTML with the tags removed)

    Extension:

    innerText、innerHTML、outerHTML、outerText

    innerText: 表示起始标签和结束标签之间的文本

    innerHTML: 表示元素的所有元素和文本的HTML代码

    如:

    Hello world
    The innerText is Hello world, and innerHTML is Hello world

    outerText: The difference from the former is that the entire target node is replaced, and the problem returns the same content as innerText

    outerHTML: The difference from the former What is replaced is the entire target node, and the complete HTML code of the element is returned, including the element itself

    A picture to understand OUTHTML, innerText, and innerHTML:

    Change HTML style (style attribute): element.style.color =red;

    3) Delete node

    ① Delete element node: To delete element node A, you need to obtain A's parent node B, the parent node can be obtained through the method in 17.1.1, or directly through ## The parentNode attribute of #A is obtained (recommended). Call B's removeChild(A) to delete the A node.

    ② Delete attribute node: You can use

    removeAttribute(attrName) or removeAttributeNode(node) of the element node to which the attribute node belongs. delete.

    ③ Clear the text node: The simplest and most common method is to directly set the

    nameNode attribute of the text node to an empty string: textNode. nodeValue ="".

    Confusion point:

    ##

    This is a text

    var p = document.getElementById('example');

    p.nodeValue //null,p

    is the element node, So

    nodeValue is null

    p.getAttributeNode('id').nodeValue //example

    , here we get the attribute node of the

    id attribute of p, nodeValue is its attribute value

    p.childNodes[0].nodeValue //This is a piece of text,

    p

    contains two For child nodes, although the inserted text has no label, it is still a node.

    Its type is a text node, and its

    nodeValue

    is the string written in it, including newlines and indentation

    p.innerHTML//This is a piece of text "

    Here

    innerHTML

    returnedpThe various values ​​contained in all nodes are in the form of strings

    ##

    4)创建和添加节点

    ① 创建节点:通过document对象的createElement(eleName)createTextNode(nodeValue)方法可分别创建元素节点和文本节点。属性节点也有自己的create方法,但是用的少,直接用元素节点的setAttribute()方法即可添加属性。

    ② 添加节点:两个重要的方法:appendChild()insertBefore(),具体见Node接口中的方法。

    扩展:上面的两个方法都是在已知父节点时用到的,也可以直接在兄弟节点后添加新节点:x.insertBefore(newNode)x.appendChild(newNode)都可以向x后追加一个新的子节点。

    5)替换节点

    主要掌握replaceChild(newNode , oldNode) 替换元素节点。(属性节点和文本节点有更简单的方法)

     

     

     

     

    2.3 DOM事件

    DOM同时两种事件模型:冒泡型事件和捕获型事件

    冒泡型事件:事件按照从最特定的事件目标到最不特定的事件目标的顺序触发

      

    Click Me

    触发的顺序是:divbodyhtml(IE 6.0Mozilla 1.0)documentwindow(Mozilla 1.0)

     

    捕获型事件:与冒泡事件相反的过程,事件从最不精确的对象开始触发,然后到最精确

    上面例子触发的顺序是:documentdiv

    DOM事件模型最独特的性质是,文本节点也触发事件(IE中不会)

    Compare the differences and connections between BOM and DOM in Javascript1)事件处理函数/监听函数

    在JavaScript中:

    var oDiv = document.getElementById("div1");

    oDiv.onclick = function(){ //onclick只能用小写

       alert("Clicked!");

    }

    或者

    var elem =document.getElementById(“id”)

    elem.onmouseover=handleMouseOver  //handleMouseOver  是函数名

    Function handleMouseOve(e){...}

     

    在HTML中:

    //onclick case is arbitrary

    Extension:

    ##IE event handler attachEvent() and detachEvent()

    In IE, each element and window object has two methods: attachEvent() and detachEvent(). These two methods accept the same two parameters, the event handler name and the event handler function. , such as:

    [object].attachEvent("name_of_event_handler","function_to_attach")

    [object].detachEvent("name_of_event_handler","function_to_remove")

    var fnClick = function(){

    alert("Clicked!");

    }

    oDiv.attachEvent("onclick", fnClick); //Add event handling function

    oDiv.attachEvent("onclick", fnClickAnother); //You can add multiple event handlers

    oDiv.detachEvent("onclick", fnClick); //Remove event handlers

    When using the attachEvent() method, the event handler will run in the global scope, so this is equal to window.

    2) Cross-browser event handler

    addHandler() and removeHandler()

    addHandler() method belongs to a class called EventUntil() Object, both methods accept the same three parameters, the element to operate on, the event name and the event handler function.

    3) Event type

    Mouse events: click, dbclick, mousedown, mouseup, mouseover, mouseout, mousemove

    Keyboard events: keydown, keypress , keyup

    HTML events: load, unload, abort, error, select, change, submit, reset, resize, scroll, focus, blur

    4) Event handler

    Programs that execute JavaScript code respond to events when they occur. Code that is executed in response to a specific event is called an event handler.

    The syntax for using event handlers in HTML tags is:

    6)DOM 0

    Level event handlerDOM Level 0 event handler: Assign a function to the handler attribute of an event

    var btn2=document.getElementById('btn2');Get btn2 button object

    btn2.onclick //Add onclick to btn2 Attribute, the attribute triggered an event handler

    btn2.onclick=function(){

    } //Add anonymous function

    btn2.onclick=null //Delete onclick attribute

    7)

    DOM 2

    level event handlerDOM Level 2 events define two methods for specifying and removing event handler operations addEventListener() and removeEventListener()

    ##addEventListener() and removeEventListener. ()

    In DOM, addEventListener() and removeEventListener() are used to allocate and remove event handling functions. Unlike IE, these methods require three parameters: event name, to be allocated Whether the functions and processing functions are used in the bubbling phase (false) or the capturing phase (true), the default is the bubbling phase false

    [object].addEventListener("name_of_event",fnhander,bcapture)

    [object].removeEventListener("name_of_event",fnhander,bcapture)

    var fnClick = function(){

    alert("Clicked!");

    }

    oDiv.addEventListener("onclick", fnClick, false); //Add event handling function

    oDiv.addEventListener("onclick", fnClickAnother, false); //Same as IE , you can add multiple event handling functions

    oDiv.removeEventListener("onclick", fnClick, false); //Remove event handling functions

    If you use addEventListener( ) to add the event handler function to the capture phase, you must indicate the capture phase in removeEventListener() to correctly delete the event handler function

    oDiv.onclick = fnClick;

    oDiv .onclick = fnClickAnother; //Use direct assignment, subsequent event processing functions will overwrite the previous processing functions

    oDiv.onclick = fnClick;

    oDiv.addEventListener("onclick", fnClickAnother, false); //Will be called in sequence and will not overwrite

    3.Browser Object Model(BOM)

    The core of BOM is window , and the window object has a dual role. It is an interface for accessing the browser window through js , is another Global (global) object. This means that any object, variable, and function defined in a web page has window as its global object.


    #3.1WindowObject

    Window

    Object is the top-level object in the JavaScript hierarchy.

    Window

    The object represents a browser window or a frame.

    Window

    The object will be in or It is automatically created when it appears.

    1) Object attributes

    window //

    Window itself, window=window. selfcan be accessed using the global property windowWindowobject

    document pair

    Document A read-only reference to the object. See Document object.

    history A read-only reference to the

    History object. Please parameter History object.

    location The

    Location object used for the window or frame. See Location object.

    screen A read-only reference to the

    Screen object. Please parameter Screen object.

    navigator A read-only reference to the

    Navigator object. Please parameter Navigator object.

    defaultStatus Sets or returns the default text in the window status bar.

    innerheight returns the height of the document display area of ​​the window.

    innerwidth returns the width of the document display area of ​​the window.

    outerheight Returns the outer height of the window.

    outerwidth returns the outer width of the window.

    pageXOffset sets or returns the

    X position of the current page relative to the upper left corner of the window display area.

    pageYOffset sets or returns the

    Y position of the current page relative to the upper left corner of the window display area.

    name Sets or returns the name of the window.

    parent Returns the parent window.

    top Returns to the topmost ancestor window.

    status sets the text of the window status bar.

    window.location //URL

    address, equipped with this property, you can open a new page

    2) Object method

    window.close(); //

    Close the window

    window.alert("message"); //

    Pop up a message with OK The system message box of the button displays the specified text

    window.confirm("Are you sure?"); //Pop up a window with OK and Cancel The button's query dialog box returns a Boolean value

    window.prompt("What's your name?", "Default"); //Prompts the user to enter information, accepts two parameters, That is, the text to be displayed to the user and the default value in the text box, the value in the text box is returned as the function value

    window.status // can temporarily change the text of the status bar

    window.defaultStatus //Default status bar information, the text can be changed until the user leaves the current page

    window.setTimeout("alert(' xxx')", 1000); //Set to execute the specified code after the specified number of milliseconds. Accepts 2 parameters, the code to be executed and the milliseconds to wait. Number

    window.clearTimeout("ID"); //Cancel the pause that has not yet been executed and pass the pauseID to it

    window.setInterval(function, 1000); //Repeat the specified code infinitely every specified time period, the parameters are the same as setTimeout()Same

    window.clearInterval("ID"); //Cancel the time interval and pass the interval ID to it

    window.history.go(-1); //Access the history of the browser window, a negative number means going back, a positive number means going forward

    window. history.back(); //Same as above

    window.history.forward(); //Same as above

    window.history.length / /You can view the number of pages in history

    clearInterval() cancels the timeout# set by setInterval() ##.

    clearTimeout() cancels the

    timeout set by the setTimeout() method.

    createPopup() Creates a

    pop-up window.

    moveBy() moves the window by the specified pixels relative to its current coordinates.

    moveTo() Moves the upper left corner of the window to a specified coordinate.

    open() Open a new browser window or find a named window.

    print() Prints the contents of the current window.

    resizeBy() Resizes the window according to the specified pixels.

    resizeTo() Resize the window to the specified width and height.

    scrollBy() Scrolls content according to the specified pixel value.

    scrollTo() Scroll the content to the specified coordinates.

    setInterval() Calls a function or evaluates an expression at a specified period (in milliseconds).

    setTimeout(

    Method,Seconds) Calls a function or calculated expression after the specified number of milliseconds.

    timeOutEvent = setTimeout("longPress('" + obj + "')",1500); timer passes parameters

    3) Member object

    window.event

    window.document //

    See documentObject details

    window.history

    window.screen

    window.navigator

    Window.external

    Extension

    ① If the document contains frames (

    frame or iframe tags), the browser will treat the HTML document Creates a window object, and an additional window object for each frame.

    window.frames Returns all named frames in the window

    parent is the parent window (if the window is a top-level window, then parent==self==top)

    top is the top-level parent window (some windows have several layers of frameset or iframe)

    self is the current window (equivalent to window)

    opener is the window that opens the current window using the open method

    ④Methods related to the message box: alert(String), confirm(String), prompt(String)

    ⑤Two timers: setTimeout(code,latency) andsetInterval(code,period)

    Note: setTimeout is only executed oncecode. If you want to call it multiple times, you can Will code itself call setTimeout(); setInteval() will Keep calling code until clearInterval() is called.

    3.2 historyObject

     window.history.length //Viewed pages Number

    history.back() //Go back one step in the browsing history

    history.forward() //Go forward in the browsing history Further

     history.go(i) //Go to the i## of the detailed historical registration form

    # 

    //i>0Progress,i<0Retreat

     

    ------------------------------------------------ -------------------

    3.3 screenObject

    screen

    Object: used to obtain certain information about the user's screen. You can also use window.screen to reference it

    window.screen. width //

    Screen width

     

    window.screen.height //Screen height

     

    window.screen .colorDepth //Screen color depth

     

    window.screen.availWidth //Available width( Remove the height of the taskbar)

     

    window.screen.availHeight //Available height(Remove the height of the taskbar)

     

    --------------------- -------------------------------- ------------------

    3.4 externalObject## 

    window.external.AddFavorite("

    Address","Title" ) //Add the website to favorites

     -------------------------------------------------- ------ -------------------

    3.5 navigatorObject

    navigator`Object: Contains a large amount of information about the Web browser, which is very useful in detecting browsers and operating systems

     window.navigator.appCodeName //Browser code name

     window.navigator.appName //Browser code Name

     window.navigator.appMinorVersion //Browser patch version

     window.navigator.cpuClass // cpuTypex86

     window.navigator.platform //Operating system typewin32

     window.navigator.plugins

     window.navigator.opsProfile

     window.navigator. userProfile

     window.navigator.systemLanguage //Customer system languagezh-cnSimplified Chinese

     window.navigator.userLanguage //User Language, Same as above

     window .navigator.appVersion //Browser version(Including system version)

      window.navigator.userAgent//String representation of the user agent header

     window.navigator.onLine //The user is online

     window.navigator.cookieEnabled //Whether the browser supports cookie

     window.navigator. mimeTypes

    3.6 DocumentObject

    1) The object attribute

    document.body// provides direct access to the element. For documents that define a frameset, this property refers to the outermost .

    document.cookie Returns all cookies related to the current document.

    document.title //Returns the document title equivalent to HTMLtitle Tag

    document.domain Returns the domain name of the current document.

    document.bgColor //Return to page background color

    document.fgColor //Return to foreground color(Text color)

    document.linkColor //Unclicked link color

    document.alinkColor // Activate the color of link (Focus is on this link)

    document.vlinkColor //Clicked link color

    document.URL //Set the URL property to open another web page in the same window

    document.fileCreatedDate //File creation date, read-only attribute

    document.fileModifiedDate //File modified date, read-only attribute

    document.lastModified Returns the date and time when the document was last modified.

    document.fileSize //File size, read-only attribute

    document.cookie //Set and readcookie

    document.charset // Returns the character set Simplified Chinese :gb2312

    document.URL Returns the URL## of the current document #.

    document.referrer Returns the

    URL of the document that loaded the current document.

    document.styleSheets

    Return a collection of style sheets,Return valueCSSStyleSheet[]

    document.styleSheets[0].cssRules.style.paddingTop=”10px”Set the style

    ,Remove hyphens from the style name,

    2) Common object methods

    document.write() //

    Dynamicly write content to the page

    document.writeln() is equivalent The difference from the

    write() method is that a newline character is written after each expression.

    document.createElement() //

    Create a new element object with the specified tag type)

    document.getElementById(ID) //

    Get the object with the specified ID#document .getElementsByName(Name) //Get the object with the specified

    Name

    #getElementsByTagName() Returns a collection of objects with the specified tag name. document.body.appendChild(oTag)————————————————————————

    3) body-

    Body sub-object

    document.body //

    Specifies the start and end of the document body, which is equivalent to body> /body>

    document.body.bgColor //

    Set or get the background color behind the objectdocument.body.link //Not yet Clicked link color

    document.body.alink //Activate link

    (Focus is on this link

    )colordocument.body.vlink //Clicked link colordocument.body.text // Text color

    document.body.innerText //Settings

    body>

    /body># Text between ##document.body.innerHTML //Settingsbody>

    /body>

    HTMLcode##document.body.topMargin //Top margin of pagedocument.body.leftMargin //Left margin of the page

    document.body.rightMargin //

    Right margin of the page

    document.body.bottomMargin //

    Bottom margin of the page

    document.body.background //

    Background image##document.body.appendChild( oTag) //

    Dynamicly generate a

    HTML

    object

    ##4) Common object events

    document.body.onclick=func()

    //The mouse pointer clicks the object to trigger

    document.body.onmouseover=func()//Triggered when the mouse pointer moves to the object

    document.body.onmouseout=func()//Mouse Triggered when the pointer moves out of the object

    ————————————————————————

    5)location- Location sub-object

    locationObject: Represents the URL of the loading window, also availablewindow.locationReference it

    location.href //The complete URL of the currently loaded page, such as http://www.somewhere.com/pictures/index.htm

    location.portocol //The protocol used in URL, that is, before the double slash part, such as http

    location.host //The name of the server, such as www.wrox.com

    location.hostname // is usually equal to host, sometimes the preceding www

    location.port is omitted //The requested port declared by URL. By default, most URL does not have port information, such as 8080

    location.pathname //The part after the host name in URL, such as /pictures/index.htm

    location.search //Execute# The part after the question mark in the URL requested by ##GET is also called the query string, such as ?param= xxxx

    location.hash //

    If URL contains #, return this symbol The following content, such as #anchor1##location.assign("http:www.baidu.com"); //

    Same as

    location .href, the new address will be added to the browser’s history stacklocation.replace("http:www.baidu.com"); //

    Same as

    assign(), but the new address will not be added to the browser's history stack and cannot be passed through back and forwardAccesslocation.reload(true | false); //

    Reload the current page, which is

    false is reloaded from the browser cache, and true is reloaded from the server. The default is false document.location.reload(URL) //

    Open a new web page

    6) selection-

    Selection sub-objectdocument.selection

    7) forms

    Collection(Form in page) a)

    Referenced through the collection

    document.forms //

    corresponds to the

    form## on the page #tagdocument.forms.length //The number of

    /formform tags on the corresponding page

    document.forms[0] //1/formformtag

    document.forms[i] //i-1/formformtag

    document.forms[i].length //i-1/formform Number of controls

    document.forms[i].elements[j] //i-1## The j-1 control in #/formform

    b)

    passes the tag The name attribute directly refers to

    /formform name=

    Myform>input name=myctrl/>/form

    document.Myform.myctrl // document.

    Form name.Control name

    c)

    Access the properties of the form

    document .forms[i].name //

    Corresponds to form name>Attribute

    document.forms[i].action //

    Corresponds to /formform action>Attribute

    document.forms[i].encoding //

    Corresponds to /formform enctype>Attribute

    document.forms[i].target //

    corresponds to/formform target>Attribute

    document.forms[i].appendChild(oTag) //

    Dynamicly insert a control

    document.all.oDiv //

    Reference layer oDiv

    document.all.oDiv.style.display=

    //Layer is set to visible

    document.all.oDiv.style.display=

    none//Layer is set to hidden

    document.getElementId(

    oDiv) //Refer to the object through getElementId

    document.getElementId(

    oDiv).style=

    document.getElementId(

    oDiv ).display=none

    /*document.all

    means # A collection of all objects in ##documentOnly

    ie

    supports this attribute, so it is also used to determine the type of browser */....

    3.7 HTMLElement

    Object

    HTML DOM

    node

    In HTML DOM (Document Object Model), each part is a node:

    1.The document itself is a document node

    2.AllHTMLElements are element nodes

    3.AllHTMLAttributes are attribute nodes

    4.HTML The text within the element is text nodes

    5.Comments are Comment Node

    Element Object

    In HTML DOM , ## The #Element object represents the HTML element.

    Element

    Objects can have child nodes of type element nodes, text nodes, and comment nodes.

    NodeList

    The object represents a node list, such as the collection of child nodes of the HTML element.

    Elements can also have attributes. The attribute is an attribute node

    Get

    document.getElementById(ID) //

    Get the object with the specified ID value

    document.getElementsByName(Name) //

    Get the object with the specified Name

    getElementsByTagName() returns the object with the specified An object collection of tag names.

    Properties and methods

    There are

    a,b parameters in the method just to deepen the explanation,The absence of a,b in other elements does not mean that it is a parameterless method

    Element.add()

    given Element adds the specified class

    element.accessKey Sets or returns the shortcut key of the element.

    element.appendChild() Adds a new child node to the element as the last child node.

    element.attributes Returns a collection of element attributes.

    element.childNodes returns the

    NodeList of the element's child nodes.

    element.className Sets or returns the

    class attribute of the element.

    element.clientHeight Returns the visible height of the element.

    element.clientWidth Returns the visible width of the element.

    element.cloneNode() Clone element.

    element.compareDocumentPosition() Compares the document positions of two elements.

    element.contentEditable Sets or returns the text direction of an element.

    element.dir Sets or returns the text direction of the element.

    element.firstChild returns the first child of the element.

    element.getAttribute() returns the specified attribute value of the element node.

    element.getAttributeNode() returns the specified attribute node.

    element.getElementsByTagName() Returns a collection of all child elements with the specified tag name.

    element.getFeature() returns an object that implements the

    API of the specified feature.

    element.getUserData() Returns the object of the key on the associated element.

    Element.hidden

    Gets or sets the existence status of hidden

    element.hasAttribute() If the element has the specified attribute, it returns

    true, otherwise it returns false.

    element.hasAttributes() Returns

    true if the element has attributes, otherwise returns false.

    element.hasChildNodes() Returns

    true if the element has child nodes, otherwise false.

    element.id Sets or returns the

    id of the element.

    element.innerHTML Sets or returns the content of the element.

    element.insertBefore(,) Inserts a new node before the specified existing child node. AInsert before b

    element.isContentEditable Sets or returns the content of the element.

    element.isDefaultNamespace() If the specified namespaceURI is the default, returns true, otherwise returns false.

    element.isEqualNode() Checks whether the a element is equal to the current element.

    element.isSameNode(a) Checks whether the specified element is the current element.

    element.isSupported() If the element supports the specified attribute, returns true.

    element.lang Sets or returns the language code of the element.

    element.lastChild returns the last child element of the element.

    element.namespaceURI Returns the namespace URI of the element.

    element.nextSibling Returns the sibling element after the current element

    element.nodeName Returns the name of the element.

    element.nodeType Returns the node type of the element.

    element.nodeValue sets or returns the element value.

    element.normalize() Merges adjacent text nodes in elements and removes empty text nodes.

    element.offsetHeight returns the height of the element.

    element.offsetWidth returns the width of the element.

    element.offsetLeft returns the horizontal offset position of the element.

    element.offsetParent returns the offset container of the element.

    element.offsetTop returns the vertical offset position of the element.

    element.ownerDocument returns the root element (document object) of the element.

    element.parentNode returns the parent node of the element.

    element.previousSibling Returns the sibling element before the current element

    Element.remove() Remove the specified class from the element

    element.removeAttribute() Removes the specified attribute from the element.

    element.removeAttributeNode() Removes the specified attribute node and returns the removed node.

    element.removeChild(a) Removes child nodes from an element.

    element.replaceChild(a,b) Replaces the child nodes in the element.

    element.scrollHeight returns the overall height of the element.

    element.scrollLeft Returns the distance between the left edge of the element and the view.

    element.scrollTop Returns the distance between the top edge of the element and the view.

    element.scrollWidth returns the overall width of the element.

    element.setAttribute() Sets or changes the specified attribute to the specified value.

    element.setAttributeNode() Sets or changes the specified attribute node.

    element.setIdAttribute()

    element.setIdAttributeNode()

    element.setUserData() Associates an object to a key on an element.

    element.style Sets or returns the style attribute of the element.

    Element.toggle()If the class does not exist, add it and remove it if it exists

    element.tabIndex sets or returns the element's tab key control sequence.

    element.tagName Returns the tag name of the element.

    element.textContent Sets or returns the text content of the node and its descendants.

    element.title Sets or returns the title attribute of the element.

    element.toString() Converts an element to a string.

    nodelist.item() returns the node located at the specified index in NodeList .

    nodelist.length returns the number of nodes in NodeList .

    element.addEventListener(event, function, useCapture)

    ##Parameters

    Description

    event

    Required. String specifying the event name.

    Note

    : Do not use the "on" prefix. For example, use "click" , instead of using "onclick".

    Tip: For all HTML DOM events, please view our complete HTML DOM Event Object Reference Manual.

    function

    Required. Specify the function to be executed when the event is triggered.

    When the event object will be passed into the function as the first parameter. The type of event object depends on the specific event. For example, the "click" event belongs to the MouseEvent(mouse event) object.

    useCapture

    Optional. A Boolean value that specifies whether the event is executed in the capture or bubbling phase.

    Possible values:

    true - The event handler is executed during the capture phase

    false- false- Default. The event handler is executed during the bubbling phase

    ##contentWindow

    Attribute

    If there is an iframe in the document

    Property Use this property to return the content of iframe

    1) Table object


    ##rows

    The collection returns all rows in the table (

    TableRow objects), the collection includes , , and # All rows defined in ##TableRow

    Object

    TableRow The

    object represents a

    HTML table row. ##In the HTML

    document Each time the tag appears, one TableRowThe object will be created. TableRow Object collection

    # #CollectionReturns an array containing all cells in the row.

    ##Description

    IE

    ##F

    ## O

    ##W3C

    ##cells[]

    4

    ##1

    9

    Yes

    cells The collection returns all

    or element.

    TableCell Object represents a HTML table cell.

    ##In a HTML document

    Each time the tag appears, a TableCellThe object will be created

    3.8 EventObject

    1) Common attributes of Event objects

    ##NameDescription ReturntypeThe name of the event is like String##target

    mouseover

    ## The element pointed to by the event

    HTMLElement

    2) Window Event attributes

    (Those without blue are allh 5 New event)

    Event triggered for window object (applied to < body>tag):

    Attribute

    onafterprint Script that runs after the document is printed.

    onbeforeprint Script that runs before document printing.

    onbeforeunload Script to run before document unloading.

    onerror Script to run when an error occurs.

    onhaschange Script that runs when the document has changed.

    onload Triggered after the page has finished loading.

    onmessage Script that runs when a message is triggered.

    You can use calling postMessage () to send a message to the main thread. In some scenarios, the business caller may need to actively communicate with the positioning component,can be passedhtml5 The postMessage method actively initiates communication with the positioning component

    onoffline A script that runs when the document is offline.

    ononline Script to run when the document comes online.

    onpagehide Script that runs when the window is hidden.

    onpageshow Script that runs when the window becomes visible.

    onpopstate Script that runs when the window history changes.

    onredo Script that runs when a document performs a revocation (redo).

    onresize Fires when the browser window is resized.

    onstorage A script that runs after the Web Storage zone is updated.

    onundo A script that runs when the document executes undo .

    onunload Fires once the page has been downloaded (or the browser window has been closed).

    3) Form Event

    Event triggered by an action within the HTML form (applies to almost All HTML elements, but most commonly used in form elements):

    Attributes

    onblur Script that runs when an element loses focus.

    onchangeScript that runs when the element value is changed.

    oncontextmenu Script that runs when the context menu is triggered.

    onfocus Script that runs when an element loses focus.

    onformchange Script that runs when the form changes.

    onforminput Script that runs when the form gets user input.

    oninput Script that runs when the element gets user input.

    oninvalid Script that runs when an element is invalid.

    onreset Fires when the reset button in the form is clicked. Not supported in HTML5.

    onselect Fires after the text in the element is selected.

    onsubmit Fires when the form is submitted.

    4)oninput,onpropertychange,onchange usage

    ##oninput:

    oninput

    The event is triggered when the user inputs.

    This event is triggered when the value of the

    or