search
HomeWeb Front-endJS TutorialIn-depth understanding of DOM and BOM in JavaScript

This article brings you relevant knowledge about javascript. It mainly introduces the difference and usage between DOM and BOM, and also includes some related operations. Let’s take a look. I hope it helps everyone.

In-depth understanding of DOM and BOM in JavaScript

[Related recommendations: javascript video tutorial, web front-end]

I. Brief Description: What is DOM and what is BOM?

At the beginning of the article, I want to mention Generally speaking, What is DOM and what is BOM, because this article The article is ultimately intended for friends who have a certain foundation in JavaScript, but do not understand or even know about DOM and BOM.

However, before talking about what is DOM and what is BOM, please allow me to show you the entire structure of Javascript:

In the picture above, we can see that there are four elements: JavaScript, ECMAScript, DOM and BOM. So what is the connection between the four of them? Use an equation to summarize the relationship between them:

JavaScript = ECMAscript BOM DOM

Let’s

compare them one by one To give an overview:

ECMAscript:

ECMAScript is a language adopted by

ECMA International (formerly the European Computer Manufacturers Association) ECMA-262 standardized scripting programming language,It is the standard for JavaScript (JS for short), and the browser is to implement this standard.

ECMAscript is more like a regulation that stipulates how each browser executes the syntax of JavaScript, because we know that JavaScript is a scripting language that runs on the browser! There are regulations, but we still lack a way to interact with each element on the page. At this time, the following DOM was born!


DOM:

DOM (

Document Object Model, Document Object Model) is a language independent, Application programming interface used to operate xml, html documents.

For JavaScript: In order to

enable JavaScript to operate Html, JavaScript has its own DOM programming interface.

One sentence summary:

DOM provides a "method" for JavaScript to access and operate HTML elements(The reason why we don’t use the word interface is because we are afraid that some friends will see the interface It’s a scary situation, but in fact the most accurate description of is that it provides an interface for JavaScript)


##BOM:

BOM is
Browser Object Model, browser object model

. BOM is an interface that appears to control the behavior of the browser. For JavaScript: In order to

allow JavaScript to control the behavior of the browser

, JavaScript has its own BOM interface.

One sentence summary:
BOM provides JavaScript with a "method" to control browser behavior.

Finally, among the above three components of JavaScript,

ECMscript is a specification

, while the other two provide "methods", respectively Corresponding to HTML elements and browsers, so below we will give a systematic explanation for the latter two: DOM and BOM. Since it is for beginners, my following explanation will be as simple as possible It’s easy to understand, even if you don’t have a basic knowledge, you can eat it with confidence!


II. DOM and its related operations

First of all, let’s

explain the relevant knowledge of DOM

, I will Divided into two pieces of content:

II.I DOM tree

Okay,

then what is a DOM tree?

Maybe some beginners who have learned DOM will be a little unfamiliar with this word, but in fact, the DOM tree is not a particularly fantasy thing. On the contrary, for front-end staff,

The DOM tree is the tree composed of the HTML elements of the pages you deal with every day:

In BOM tree, Each node can have two identities: it can be a child node of the parent node, or it can be the parent node of other child nodes. Let’s observe the following paragraph together. Code :

nbsp;html>


    <meta>
    <title>DOM_demo</title>


    <p>
        <a>跳探戈的小龙虾</a>
    </p>

The above code, its DOM tree should be like this:

At this time someone wants I asked, you said that the DOM tree for so long has something to do with operating html elements?

The answer is is very relevant, and only by understanding the DOM tree structure of the document can we accurately and effectively operate DOM elements , otherwise various unexpected bugs will appear. Before we operate the HTML elements of a page, we must have a clear drawing of the DOM of the entire page. Even if we are not actually drawing, we must have a clear context structure in our mind.


II.II Some common methods of operating elements of DOM

AboutSome common operations of DOM in JavaScript The method of html element, I have divided it into several sub-parts to introduce them to you:

The DOM method of getting the node
//1.通过元素的id属性值来获取元素,返回的是一个元素对象
var element = document.getElementById(id_content)

//2.通过元素的name属性值来获取元素,返回的是一个元素对象的数组
var element_list = document.getElementsByName(name_content)

//3.通过元素的class属性值来获取元素,返回的是一个元素对象的数组
var element_list = document.getElementsByClassName(class_content)

//4.通过标签名获取元素,返回的是一个元素对象数组
var element_list = document.getElementsByTagName(tagName)


DOM method to get/set the attribute value of an element
//1.获取元素的属性值,传参自然地是属性名,例如class、id、href
var attr = element.getAttribute(attribute_name)

//2.设置元素的属性值,传参自然地是元素的属性名及要设置的对应的属性值
element.setAttribute(attribute_name,attribute_value)


DOM method to create a node(Node)
//1.创建一个html的元素,传参是元素类型,例如p、h1-5、a,下以p为例
var element = document.createElement("p")

//2.创建一个文本节点,传参的是对应的文本内容(注意是文本节点,不是某个html元素)
var text_node = document.createTextNode(text)

//3.创建一个属性节点,传参是对应的属性名
var attr_node = document.createAttribute(attribute_name)
element.setAttributeNode(attr_node)

Special attentionThe third method of creating attribute nodes must be matched with a specific element, that is, you mustget a specific element element first and create a Attribute node, finally add this attribute node (setAttributeNode) to this element.


DOM method of adding nodes
//1.向element内部的最后面添加一个节点,传入的参数是节点类型
element.appendChild(Node)

//2.向element内部某个已存在的节点的前面插入一个节点,仍然传入一个节点类型的参数
element.insertBefore(new_Node,existed_Node)

Note, Before adding a node, you need to Create the node first, and select the parent node element at the same time. The second method Even you have to find the sibling node behind the insertion position.


DOM method of deleting a node
//删除element内的某个节点,传参是节点类型参数
element.removeChild(Node)

Note, When deleting, you must find the corresponding parent node element. Successfully deleted .


Some common DOM attributes

Finally,

Some common DOM attributes:

//1.获取当前元素的父节点
var element_father = element.parentNode

//2.获取当前元素的html元素型子节点
var element_son = element.children

//3.获取当前元素的所有类型子节点,包括html元素、文本和属性
var element_son = element.childNodes

//4.获取当前元素的第一个子节点
var element_first = element.firstChild

//5.获取当前元素的前一个同级元素
var element_pre = element.previousSibling

//6.获取当前元素的后一个同级元素
var element_next = element.nextSibling

//7.获取当前元素的所有文本,包括html源码和文本
var element_innerHTML = element.innerHTML

//8.获取当前元素的所有文本,不包含html源码
var element_innerTEXT = element.innerText
Among them, the seventh meaning of

is that means to convert the html code and text in the element into text . The original html code is executed, and converting it into text is equivalent to Ordinary string!


III. BOM and related operations

III.I Overview of BOM

We will talk about it below Let's talk about BOM. Due to

limited space, BOM will not be explained in detail (its practicality is indeed not as great as DOM). Let’s review the introduction to BOM at the beginning:

BOM provides JavaScript with several "methods" to operate the browser

So first we
use a picture to sort out the structure of the entire BOM. Similar to the DOM, the BOM also has a tree structure:


III.II Introduction to common BOM objects

window object

From the above picture, we You can see:

window is the top of the entire BOM tree food chain

, so every newly opened window is considered a window object.

The window object has the following
common properties and methods

:

Properties/Methods Meaning
opener The parent window of the current window
length The number of frames in the window
document The document object currently displayed in the window
alert(string) Create a warning dialog box and display a message
close() Close the window
confirm() Create a dialog box that requires user confirmation
open(url,name,[options]) Open a new window and return the new window object
prompt(text,defaultInput) Create a dialog box to ask the user to enter information
setInterval(expression, milliseconds) Calculate an expression after a specified time interval
setInterval(function,millis enconds,[arguments]) Call a function after the specified time interval
setTimeout(expression,milli seconds) Calculate an expression after the timer expires
setTimeout(expression,milli seconds,[arguments]) Calculate an expression after the timer expires Function

Among them, you can see that there is a function alert() on it, because when you learn JavaScript, the input and output streamsEveryoneMost of them use the alert() function pop-up window as their first demo, so when you see this you may ask:

At that time

Used alert() When it comes to functions, it seems that window is not mentioned, so is the alert() here the same alert() that I learned before? The answer is this:

These

two alert() are indeed the same function . The reason why window can be omitted is because all the properties and methods of window , can have two representation methods:

(1) window.property/window.method()

(2) direct property / Calling method ()

is not just alert(), all the above window properties and functions are established, and interested friends can try it by themselves.


location object

What is the

location object?

The location object is a property of the window object, which provides information about the document loaded in the current window and also provides some navigation functions.

The location object has the following common properties and methods:

##hosthostnamehref##pathnamePathnameportPort numberprotocolProtocol part searchQuery stringreload()Reload the current URLrepalce() Replace the current page with the new URL

In fact, if we carefully observe the structure diagram above, we will find:

The location object is not only an attribute of the window object, but also an attribute of the document object.

This means:

##window.location = location = document.location


history object

What is the

history object?

The history object is an attribute of the window object. It saves the record of the user's Internet access. The timestamp of this record is calculated from the moment the window was opened.

The history object has the following common properties and methods:

Properties/Methods Content
Host name: port number
Hostname
Entire URL
lengthThe number of records in the history objectback()Go to the URL of the previous browser history entry, similar to backforward()Go to the next URL of browser history entry, similar to forwardgo(num)The browser moves forward or backward in the history object
Properties/Methods Description

navigator object

Finally introduce the

navigator object:

The navigator object is the one in the BOM that identifies the client browser. window attribute.

Some common properties related to navigator:

appNameComplete browser name and version informationplatformThe system platform where the browser is locatedpluginsArray of plug-in information installed in the browseruserAgentThe browser’s user agent stringuserLanguageThe operating system’s default language
Properties Description
[Related recommendations:

javascript video tutorial, web front-end]

The above is the detailed content of In-depth understanding of DOM and BOM in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools