Javascript Study Notes (3) BOM and DOM explanation, bomdom

Source: Internet
Author: User

Javascript Study Notes (3) BOM and DOM explanation, bomdom

Js Composition

We all know that,javascriptIt consists of three parts,ECMAScript,DOMAndBOMAccording to the host (browser), the specific expressions are also different. ie and other browsers have different styles.

1. DOM is W3C standard; [common standards for all browsers]
2. BOM is used by various browser vendors according to DOM
Implementation on the respective browsers; [different definitions are displayed in different browsers, with different implementation methods]
3. window is a BOM object, not a js object;

DOM(Document Object Model) isHTMLAndXMLApplication Interface (API).

BOMMainly deal with browser windows and frameworks, but usually the browser-specificJavaScriptAll extensions are considered part of BOM. These extensions include:

Pop up a new browser window, move it, close the browser window, and adjust the window size. The location object provides detailed information about the Web browser. The Screen Object provides detailed information about the user's screen resolution. The cookie support IE extends the BOM, added the ActiveXObject class. ActiveX objects can be instantiated using JavaScript.

javacsriptYes through accessBOM(Browser Object Model) Object to access, control, modify the client (Browser), becauseBOMOfwindowContainsdocument, The properties and methods of the window object can be directly used and perceived, so you can directly usewindowObjectdocumentAttribute, throughdocumentYou can access, retrieve, and modify the content and structure of the XHTML document. BecausedocumentThe Object is the root node of the DOM (Document Object Model) Model. It can be said that BOM containsDOM(Object), the browser provides the BOM object for access, from the BOM object toDOMSo that js can operate the files read by browsers and browsers. Where
DOM includes:window

Window objects include attributes: document, location, navigator, screen, history, and framesDocument. The root nodes include subnodes: forms, location, anchors, images, and links.

Slavewindow.documentWe can see that the most fundamental object of DOM is the sub-object of the window object of BOM.

Difference: DOM describes the methods and interfaces used to process web content. BOM describes the methods and interfaces used to interact with browsers.

Understanding DOM

Let's take a look at the following code:

<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 

Break down the HTML code into a DOM node hierarchy:

** HTML documents can be said to be a collection composed of nodes. DOM nodes include: ** 1. element nodes: 

Node attributesNode attributesNodeName returns a string whose content is the node name nodeType and returns an integer. This value represents the node type nodeValue and returns the current value of the given node.

Traverse node treeTraverse node treeChildNodes returns an array, this array consists of the Child Nodes of the given element. firstChild is returned. The first child node lastChild is returned. The last child node parentNode is returned. The parent node nextSibling of the given node is returned. The next child node of the given node is returned. the previous subnode

DOM operationsDOM operationsCreatElement (element) create a new element node creatTextNode () create a new text node that contains the given text appendChild () add a new subsection insertBefore () after the last node list of the specified node to insert a given node to the removeChild () before the given element node to the child node () delete a child node from a given element replaceChild () replace one child node in a given parent element with another node.

DOM expresses a document by creating a tree and describes the methods and interfaces for processing webpage content. This gives developers unprecedented control over the content and structure of the document, you can use DOM APIs to easily Delete, add, and replace nodes.

1. Access the node

'Var oHtml = document.doc umentElement; '// return the document root node that exists in XML and HTML documents. oHtml contains an HTMLElement object 'document. body '// is a special extension of the HTML page. It provides direct access to the <body> tag </span> 'document. getElementById ("ID") '// returns an element with the specified ID. getElementById () cannot work in XML. IE6 also returns the 'document. getElementByName ("name") '// obtain all elements whose name attribute is equal to the specified value, however, on IE6 and Opera7.5, only the elements with the specified id are returned, and only <input/> and  'var x = document . GetElementsByTagName ("p"); '// use the specified tag name to return the list of all elements. The index number starts from 0. When the parameter is an asterisk, IE6 does not return all elements and must be replaced by document. all.

2. Features and methods of Node nodes

FirstChild // Node, pointing to the first Node in the childNodes list, lastChild // Node, pointing to the last Node parentNode // Node in the childNodes list, pointing to the parent Node ownerDocument // Document, the document firstChild // Node to which the Node belongs, points to the first Node lastChild // Node in the childNodes list, and points to the last Node parentNode // Node in the childNodes list, point to the parent Node childNodes // NodeList. The list of all child nodes is previussibling/Node./indicates the forward sibling Node. If this Node is the first Node, the value is null 'nextsibling' // Node pointing to the next sibling Node: If this Node is the last Node, the value is null 'haschildnodes () '// Boolean, returns the true value when childNodes contains one or more nodes.

3. DOM events

DOM has two types of event models at the same time: bubble events and capture events. Bubble events: an event is triggered in the order from the most specific event target to the least specific event Target. <body onclick = "handleClick ()"> <div onclick = "handleClick () "> Click Me </div> </body>: div, body, html (IE 6.0 and Mozilla 1.0), document, window (Mozilla 1.0) capture event: the opposite process of a bubble event. The event is triggered from the most inaccurate object, and then to the most precise trigger sequence in the preceding example: the most unique feature of document and div DOM event models is that text nodes also trigger events (not in IE ).

4. event processing functions/listener Functions

** Event processing function/listener function ** in JavaScript: var oDiv = document. getElementById ("div1"); oDiv. onclick = function () {// onclick can only be in lower case. The default value is the bubble event alert ("Clicked! ");} In HTML: <div onclick =" javascript: alert ("Clicked! ")"> </Div> // The onclick is case-insensitive.

IE event handler attachEvent () and detachEvent ()

In IE, each element and window object have two methods:AttachEvent () and detachEvent ()The two methods accept two identical parameters, the event handler name and the event handler function, such:

[Object]. attachEvent ("name_of_event_handler", "function_to_attach") [object]. detachEvent ("dependencies", "function_to_remove") var fnClick = (function) {alert ("Clicked! ");} ODiv. attachEvent ("onclick", fnClick); // Add the event processing function oDiv. attachEvent ("onclick", fnClickAnother); // you can add multiple event handler functions (oDiv. detachEvent ("onclick", fnClick); // remove the event handler

In useattachEvent()In this case, the event handler will run in the global scope, so this is equal to window.

Cross-browser event handlers

AddHandler () and removeHandler ()

addHandler()The method belongs to an object named EventUntil (). Both methods accept three identical parameters, elements to be operated, event names, and event handler functions.

Event Type

** Event type **: click, dbclick, mousedown, mouseup, mouseover, mouseout, and mousemove Keyboard Events: keydown, keypress, and keyup HTML events: load, unload, abort, error, select, change, submit, reset, resize, scroll, focus, blur

Event Processor

Programs that execute JavaScript code will respond to the event when the event occurs. To respond to a specific event
The executed code is called an event processor.

The syntax for using the event processor in HTML tags is:

<HTML Tag event processor = "JavaScript code''>

Event Handler

An event is an action performed by a user or a browser. For exampleclick,mouseup,keydown,mouseoverIs the name of the event. The function that responds to an event is called the event handler (event listener ).onThereforeclickThe event handler isonclick

DOM 0-level event handler

DOM 0-level event handler: assign a function to the handler attribute of an event

<Input type = "button" value = "button 2" id = "ben2"/> var btn2 = document. getElementById ('btn2'); get the btn2 Button Object btn2.onclick // Add the onclick attribute to btn2, and the attribute triggers an event handler btn2.onclick = function () {}// Add the anonymous function btn2.onclick = null // Delete the onclick attribute

How to prevent bubbles?

You can use the following methods to prevent bubbles:

e.cancelBubble=true;e.stopPropagation();return false;

InnerText, innerHTML, outerHTML, outerText

InnerText, innerHTML, outerHTML, and outerText innerText: indicates the text innerHTML between the start tag and the end tag: indicates the HTML code of all elements and text of the element, for example: innerText of <div> <B> Hello </B> world </div> is Hello world, and innerHTML is Hello world outerText. The difference between innerText and innerHTML is to replace the entire target node, returns the same content as innerText outerHTML: the difference with the former is that it replaces the entire target node and returns the complete HTML code of the element, including the element itself.

DOM Level 2 event handler

DOM Level 2 events define two methods for specifying and deleting the operations of event handlers.addEventListener()AndremoveEventListener()

AddEventListener () and removeEventListener ()

In DOM, addEventListener () and removeEventListener () are used to allocate and remove Event Handlers. Unlike IE, these methods require three parameters: event name, the functions and processing functions to be allocated are used for the bubble stage (false) or the capture stage (true). The default value is the bubble stage 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 the event processing function oDiv. addEventListener ("onclick", fnClickAnother, false); // Like IE, you can add multiple event handler functions (oDiv. removeEventListener ("onclick", fnClick, false); // remove the event handler. If you use addEventListener () to add the event handler to the capture stage, you must () in order to correctly Delete this event handler function from oDiv. onclick = fnClick; oDiv. onclick = fnClickAnother; // use direct value assignment. Subsequent event processing functions will overwrite the previous processing function oDiv. onclick = fnClick; oDiv. addEventListener ("onclick", fnClickAnother, false); // calls in sequence without Overwriting

An image shows OUTHTML, innerText, and innerHTML:

DOM basic operation Mind Map

For more details about the attributes and methods of the xml dom-Element Object, visit w3cshool.

BOM Section

BOMThe core iswindow, AndwindowThe object has a dual role. It is both an interface for accessing the browser window through js and an interface for accessing the browser window.Global(Global) object. This means that any objects, variables, and functions defined in the web page use window as theirglobalObject.

Window. close (); // close the window. alert ("message"); // a system message box with the OK button is displayed, showing the specified text window. confirm ("Are you sure? "); // A dialog box with the OK and Cancel buttons is displayed. A boolean window. prompt (" What's your name? "," Default "); // prompt the user to enter the information and accept two parameters, that is, the text to be displayed to the user and the Default value in the text box. Return the value in the text box as the function value window. status // Changes the text of the status bar to window temporarily. defaultStatus // The default status bar information. You can change the text window until the user leaves the current page. setTimeout ("alert ('xxx')", 1000); // you can specify two parameters to run the Specified Code after the specified number of milliseconds, the code to be executed and the number of milliseconds to wait window. clearTimeout ("ID"); // cancel the pause that has not been executed, and pass the pause ID to the window. setInterval (function, 1000); // repeats the Specified Code at intervals of an infinite number of times. The parameter is the same as setTimeout () window. clearInterval ("ID"); // cancel the interval and pass the interval ID to window. history. go (-1); // history of accessing the browser window. The negative value is backward, and the positive value is forward window. history. back (); // same as window. history. forward (); // same as window. history. length // you can view the number of pages in the history

Document Object

Document Object: it is actually the property of the window object. document = invalid argument Doc ument is true, which is the only document that belongs to both BOM and DOM. lastModified // gets the string representing the date of the last modification page. referrer // document used to track the user's link. title // obtain the title of the current page, which can read and write documents. URL // obtain the URL of the current page to read and write documents. anchors [0] or document. anchors ["anchName"] // access all the anchored documents on the page. forms [0] or document. forms ["formName"] // access all form documents on the page. images [0] or document. images ["imgName"] // access all images on the page document. links [0] or document. links ["linkName"] // access all links on the page document. applets [0] or document. applets ["appletName"] // access all the Applet documents on the page. embeds [0] or document. embeds ["embedName"] // access all the embedded object document on the page. write (); or document. writeln (); // insert strings to the location where they are called

Location object

Location object: indicates the URL of the loading window. window is also available. location references its location. href // The complete URL of the currently loaded page, such as the http://www.somewhere.com/pictures/index.htm location. the protocol used in the portocol // URL, that is, the section before the double slash, such as http location. host // The name of the server, such as www.wrox.com location. hostname // usually equal to host, and sometimes the previous www location is omitted. port // The request port declared by the URL. By default, most URLs do not have port information, such as 8080 location. pathname // The part after the host name in the URL, such as/pictures/index.htm location. search // The part after the question mark in the URL where the GET request is executed, also known as the query string, such? Param = xxxx location. hash // If the URL contains #, the content after the symbol is returned, for example, # anchor1 location. assign ("http: www.baidu.com"); // same as location. href, the new address will be added to the browser's historical stack location. replace ("http: www.baidu.com"); // same as assign (), but the new address is not added to the browser's history stack and cannot be accessed through back and forward. reload (true | false); // reload the current page. If it is false, it is reloaded from the browser cache. If it is true, it is reloaded from the server. The default value is false.

Navigator object

'Navigator' object: contains a large amount of information about the Web browser, which is very useful in detecting browsers and operating systems and can also be used in windows. navigator references it 'navigator. appcodename' // The character string of the browser code name to indicate navigator. appName // the string of the official browser name to indicate navigator. appVersion // the string of the browser version information to indicate navigator. cookieEnabled // If cookie is enabled, true is returned. Otherwise, false navigator is returned. javaEnabled // If java is enabled, true is returned. Otherwise, false navigator is returned. platform // the string of the computer platform where the browser is located represents navigator. plugins // plug-in array navigator installed in the browser. taintEnabled // If data corruption is enabled, true is returned; otherwise, false navigator is returned. userAgent // string representation of the User Agent header

Screen Object

Screen Object: used to obtain information about the user's screen. screen references screen. width/height // the width and height of the screen, measured in pixels. availWidth/availHeight // the width and height of the screen that can be used by the window, in pixels. colorDepth // The number of digits in the color. Most systems use 32-bit windows. moveTo (0, 0); window. resizeTo (screen. availWidth, screen. availHeight); // fill in the user's screen

Window object Method

Structure Relationship between BOM and DOM


Window object Mind Map


What is the difference between the BOM of JavaScript and DOM?

Both are required.
BOM is a browser object model used to obtain or set browser attributes and behaviors, such as creating a window, obtaining screen resolution, and browser version number.
DOM is a Document Object Model Used to obtain or set the attributes of tags in a document, for example, to obtain or set the value of an input form.
BOM does not have much content, mainly DOM.

DOM has no direct relationship with the browser because its operation object is Document.

What is the difference between BOM and DOM in javascript?

1. ECMAScript is the core of javascript;
2. The core of BOM is windows, which indicates a browser instance. Any custom object, variable, and function on the webpage uses windows as its global object;
3. DOM is an API for HTML and XML documents;

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.