Compare the differences and connections between BOM and DOM in Javascript
巴扎黑
Release: 2017-08-09 11:18:14
Original
1325 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.
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 windowMove, close and resize the browser windowProvide
Web Location object for browser details
Screen object that provides detailed information about the user's screen resolutionSupport for
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, Browser 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:
1) 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 nullnextSibling //Node, pointing to the next sibling node: if this node is the last node, then the value is nullhasChildNodes()` //Boolean, when When childNodes contains one or more nodes, return true value
2) 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接口中的方法。
##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.
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].removeEventListener("name_of_event",fnhander,bcapture)var fnClick = function(){ alert("Clicked!"); }oDiv.addEventListener("onclick", fnClick, false); //Add event handling functionoDiv.addEventListener("onclick", fnClickAnother, false); //Same as IE , you can add multiple event handling functions oDiv.removeEventListener("onclick", fnClick, false); //Remove event handling functionsIf 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 functionoDiv.onclick = fnClick;oDiv .onclick = fnClickAnother; //Use direct assignment, subsequent event processing functions will overwrite the previous processing functionsoDiv.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.