Table of Contents
I. Brief description: What is DOM and what is BOM?
First of all, let’s
II.II DOM的一些常见的操作元素方法" >II.II DOM的一些常见的操作元素方法
 获取节点的DOM方法" > 获取节点的DOM方法
获取/设置元素的属性值的DOM方法" >获取/设置元素的属性值的DOM方法
创建节点(Node)的DOM方法" >创建节点(Node)的DOM方法
增添节点的DOM方法" >增添节点的DOM方法
 删除节点的DOM方法" > 删除节点的DOM方法
DOM常见的一些属性" >DOM常见的一些属性
III. BOM及其相关操作
III.I BOM总述" >III.I BOM总述
III.II BOM常见对象的介绍" >III.II BOM常见对象的介绍
window对象" >window对象
Home Web Front-end JS Tutorial Completely master the differences and usage of DOM and BOM in JavaScript

Completely master the differences and usage of DOM and BOM in JavaScript

Apr 02, 2022 pm 01:03 PM
javascript

This article brings you relevant knowledge about javascript, which mainly introduces DOM and BOM and related issues about their differences and usage. Let’s take a look at them together. I hope it will be helpful to everyone. help.

Completely master the differences and usage of DOM and BOM in JavaScript

[Related recommendations: javascript video tutorial]

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

At the beginning of the article, I would like to mention Generally speaking, what is DOM and what is BOM, because this article is ultimately intended for I am a friend who has a certain JavaScript foundation, but does not understand DOM and BOM, or even doesn't know it.

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 divided it into two parts

II.I DOM tree

Okay,

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,

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

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 code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>DOM_demo</title>
</head>
<body>
    <p>
        <a href="https://blog.csdn.net/qq_52736131">跳探戈的小龙虾</a>
    </p>
</body>
</html>
Copy after login
The above code, Its

DOM tree

should look like this:

这时候有人要问了,你说这么半天的DOM树,跟操作html元素有关吗

答案是非常有关,而且只有了解了文档的DOM树结构,才能准确而有效的操作DOM元素,否则会出现各种意料之外的bug。在我们操作一个页面的HTML元素之前,要对整个页面的DOM有一个清晰的绘图,即使在不实实在在绘图,也要在脑中有一个清晰的脉络结构。


II.II DOM的一些常见的操作元素方法

关于JavaScript中DOM的一些常见的操作html元素的方法,我又双叒叕分成几个子部分给大家归类介绍:

 获取节点的DOM方法

//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)
Copy after login

获取/设置元素的属性值的DOM方法

//1.获取元素的属性值,传参自然地是属性名,例如class、id、href
var attr = element.getAttribute(attribute_name)

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

创建节点(Node)的DOM方法

//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)
Copy after login

特别注意第三个,创建属性节点这个方法,要搭配具体的元素,也就是你要先获取某个具体元素element,创建一个属性节点,最后对这个元素添加这个属性节点(setAttributeNode)


增添节点的DOM方法

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

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

注意,添加节点之前,你要先创建好节点,同时要选好父节点element第二个方法甚至你还要找好插入位置后面的兄弟节点


 删除节点的DOM方法

//删除element内的某个节点,传参是节点类型参数
element.removeChild(Node)
Copy after login

注意,删除时,要找到对应的父节点element才可以顺利删除


DOM常见的一些属性

最后是一些常见的DOM属性

//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
Copy after login

其中,第七个的意思是说把元素内的html代码和文本都转成文本,原先的html代码是执行的,转成文本相当于变成了普通的字符串!


III. BOM及其相关操作

III.I BOM总述

下面我们再讲一讲BOM,由于篇幅有限,BOM不做特别细致的讲解(实用性的确也没有DOM那么大)。我们回顾一下开始的时候关于BOM的介绍

BOM给JavaScript提供用来操作浏览器的若干的"方法"

那么首先我们用一张图把整个BOM的结构给大家梳理一下,与DOM类似,BOM也有一个树状结构:


III.II BOM常见对象的介绍

window对象

从上面这张图上,我们可以看到:

window是整个BOM树食物链的顶端,因此每一个新打开的窗口,都被认为是一个window对象。

window对象有以下常见的属性和方法

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
The above is the entire content of this issue.

Friends who like can support it three times in a row! ???!

In addition, this blog has participated in [Rising Star Project], please support ???!

[Related recommendations:

javascript video tutorial]

The above is the detailed content of Completely master the differences and usage of DOM and BOM in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles