search
HomeWeb Front-endJS TutorialHow JavaScript uses HTML DOM to operate documents_javascript skills

HTML DOM tree

1. Introduction to DOM

DOM is a standard developed by the W3C for accessing structured documents such as XML and XHTML.

The W3C Document Object Model (DOM) is a platform- and language-neutral interface that enables programs and scripts to dynamically access and update the content, structure, and style of a document

Core DOM: the standard model for any structured document

XML DOM: Standard model for XML documents. Is a standard for getting, changing, adding or removing XML elements.

HTML DOM: The standard model for HTML documents. Defines the objects and properties of all HTML elements, as well as the methods (interfaces) to access them.

2. DOM node

According to the DOM specification, each component in the document is a node. DOM regulations:

The entire document is a document node, also called the root node

Each tag is an element node

The text contained in the tag is a text node

Each attribute of the tag is an attribute node

The annotation belongs to the annotation node

2.1DOM interface and its properties and methods

DOM simulates the document as a series of node interfaces. Nodes can be accessed through JavaScript or other programming languages. Yes

The programming interface of DOM is defined through a set of standard properties and methods.

2.1.1DOM Properties

Some typical DOM attributes:

x.nodeName: name of x

x.nodeValue: value of x

x.parentNode: the parent node of x, except the root node, there is only one parent node

x.childNodes: The child node of x, there can be multiple child nodes

x.attributes: a collection of attribute nodes of x, which can have multiple attributes

Where, x is a node object

2.1.2DOM method

Some typical DOM methods:

x.getElementsByTagName(name): Get all elements with the specified tag name

x.appendChild(node): Insert a child node into x

x.removeChild(node): Remove child node from x

Example:

//获得文档标题的文本内容
document.getElementsByTagName("title")[0].childNode[0].nodeValue

2.1.3 Access Node

Method 1: By using the getElementsByTagName() method

Method 2: Traverse the node tree through a loop

Method 3: Navigate in the node tree by leveraging node relationships

2.1.4 Node information :

nodeName: Get the name of the node, it is read-only.

nodeValue: Get or set the value of the node

nodeType: The type of node, which is read-only. 1, represents element, 2 represents attribute, 3 represents text, 8

represents comments, 9 represents documentation

3. Node operation

3.1 Create Node

createElement(tagName): Create element node

createTextNode(text): Create text node

createAttribute(attrName): Create attribute node

3.2 Add Node

The newly created node needs to be organized with other existing nodes in order for it to truly belong to the document tree.

appendChild(node) adds a new child node after the last child node inside the current node, and the parameter is the new child node

insertBefore(newNode,node) adds a new child node before the child node specified inside the current node. The first parameter is the new child node, and the second parameter is the child node specified inside the current node

insertAfter() adds a new child node after the child node specified inside the current node. The first parameter is the new child node, and the second parameter is the child node specified inside the current node

setAttributeNode() sets the attribute node on the current element node. The type of the node that invites this method to be called is the element type, and the parameter is the attribute node to be set

Example:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>使用DOM创建并添加节点</title>
<script type="text/javascript">
function createAndAddNode(){
//div标签元素节点
var container = document.body.getElementsByTagName("div")[0];
//创建元素节点对象,元素名即标签名 <p>
var pEle = document.createElement("p");
//创建文本节点对象,文本内容就是参数值
var txtOfP = document.createTextNode("这是段落的文字");
//在元素节点内部添加一个文本节点<p>这是段落的文字
pEle.appendChild(txtOfP);
//在div元素节点后面添加新的子节点。<div><p>这是段落的文字</div>
container.appendChild(pEle);
//创建一个超链接标签节点
var aEle = document.createElement("a");
//创建文本节点
var txtOfA = document.createTextNode("博客园");
//在元素节点中添加文本节点,<a>博客园</a>
aEle.appendChild(txtOfA);
//创建一个href属性节点
var attrOfA = document.createAttribute("href");
//将href属性节点设置其属性值
attrOfA.nodeValue = "http:www.cnblogs.com";
//将属性节点添加到超链接元素节点中,即设置a元素标签的属性节点
aEle.setAttributeNode(attrOfA);
//将元素节点a添加到div中
container.appendChild(aEle);
}
//浏览器窗口加载时调用该方法
window.onload = createAndAddNode;
</script>
</head>
<body>
<div></div>
</body>
</html>

3.3 Modify nodes

Changing nodes generally refers to changing the text inside the element, or changing the attribute value of the element. In both cases, you can change the text node or attribute node by assigning a value to its nodeValue. For the latter, ok

Call the setAttribute method on the element node to change the attribute value.

Example:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>使用DOM改变节点</title>
<script type="text/javascript">
function changeSize(){
var target = document.getElementById("txt_1");
//设置列的属性值为50
target.setAttribute("cols", "50");
//设置行的属性值为6 先访问属性节点集合,然后通过getNamedItem定位属性名,
target.attributes.getNamedItem("rows").nodeValue = "6";
}
function changeText() {
var target = document.getElementById("lbl_1");
//先访问该元素节点的子节点,子节点个数可以是多个,因此用了数组下标访问指定元素。然后通过nodeValue修改其值
target.childNodes[0].nodeValue = "您的个人简历:";
}
</script>
</head>
<body>
<form action="">
<label id="lbl_1" for="txt_1">多行文本框的标签文字</label>
<textarea id="txt_1" ></textarea>
<input type="button" name="btn" value="改变多行文本域的尺寸" onclick="changeSize();" />
<input type="button" name="btn" value="改变标签的文字" onclick="changeText();" />
</form>
</body>
</html>

3.3 Delete Node

Deleting a node generally refers to deleting sub-elements or text contained in an element from within an element node. It can also be used to delete attribute nodes contained in an element node

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>使用DOM删除节点</title>
<script type="text/javascript">
function doRemoveNode() {
//label标签元素节点
var targetLbl = document.getElementById("lbl_1");
//从label元素节点中删除第一个子节点
targetLbl.removeChild(targetLbl.firstChild);
//文档元素,通过访问文档元素集合,指定位置元素获得多行文本域
var tagetArea = document.documentElement.getElementsByTagName("textarea")[0];
//文档中第一个form标签元素节点
var tagetForm = document.documentElement.getElementsByTagName("form")[0];
//删除文档中第一个form标签中的textarea
tagetForm.removeChild(tagetArea);
}
</script>
</head>
<body>
<form>
<label id="lbl_1" for="txt_1">多行文本框的标签文字</label>
<textarea id="txt_1" rows="" cols=""></textarea>
<input type="button" name="btn" value="删除节点" onclick="doRemoveNode();"/>
</form>
</body>
</html>

4. Summary

DOM is the tree structure in which documents are represented in memory, called the DOM tree; DOM is the standard method and attribute developed by W3C for accessing documents, called the DOM interface
Each data in the document is represented as a node on the tree structure, and the tree structure composed of all nodes is called a node tree or DOM tree
There are many types of nodes, the common ones are element nodes, attribute nodes, text nodes, root nodes, etc. Nodes have names and values, but different types of nodes have different meanings of names and values

The createElement() method is used to create element nodes, the createAttribute() method is used to create attribute nodes, and the createTextNode() method is used to create text nodes. To add child element nodes or text nodes to element nodes, you can use appendChild() method. There are also insertAfter() and insertBefore() methods for inserting new nodes before and after specific nodes. It should be noted that the method to add attribute nodes to element nodes is the setAttributeNode() method.

To modify the value of a text node or change the value of an attribute node, you should use the nodeValue attribute

To delete a node use the removeChild() method.

As for how JavaScript uses HTML DOM to operate documents, the editor will introduce you to this much. I hope it will be helpful to you!

Statement
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
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

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 Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

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),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment