This article brings you relevant knowledge about javascript, which mainly introduces issues related to DOM node attributes. The attributes of DOM nodes depend on their classes. Let’s take a look at them together. I hope everyone has to help.

[Related recommendations: javascript video tutorial, web front-end]
After reading the previous articles Study and have a certain understanding of DOM. But this is just some basic knowledge of DOM. If you want to know more about DOM, you need to have a deeper understanding of DOM nodes. In this section, we will focus on the node attributes, labels and content of the DOM. So we can learn more about what they are? and their most common attributes.
DOM node class
The properties of DOM nodes depend on their class(class). For example, the <a></a> tag corresponds to the attributes related to an element node and the link a. Text nodes are different from element nodes, but they also have the same properties and methods because all DOM nodes will form a DOM tree.
Each DOM node belongs to the corresponding built-in class.
root is the EventTarget of the DOM tree, which is inherited by Node, and other DOM nodes inherit it.
The following figure can help us understand it easier:

The main classes of DOM nodes are:
EventTarget: It isrootAbstract Class. Objects of this class are never created. It serves as a basis, so all DOM nodes support so-called events (Events), which will be covered later-
Node: It is also an abstract class that serves as the basis of DOM nodes. It provides core functionality:parentNode,nextSibling,childNodes, etc. (they aregetter). The object of node class is not created. However, there are some specific node classes that inherit it, such as:Textfor text nodes,Elementfor element nodes, andCommentfor comment nodes, etc. Element: It is the basic class of DOM elements. It provides element-level search, such asnextElementSibling,childern,getElementsByTagName,querySelector, etc. In the browser, there are not only HTML, but also XML and SVG documents. Element classes are the basis for more concrete classes, such asSVGElement,XMLElement, andHTMLElementHTMLElement: is the basic class of HTML elements, which is inherited by various HTML elements. For example,HTMLInputElemnt(corresponding to the class of theinputelement),HTMLBodyElement(corresponding to the class of thebodyelement) andHTMLAnchorElement(Corresponding to the class ofaelement) etc.
For the
HTMLElementclass, there are many other types, such as the one shown in the figure below These.

# Therefore, all properties and methods of the node are the result of inheritance!
For example, the <input> element in the DOM object. It belongs to the HTMLInputElement class in the HTMLElement class. It stacks properties and methods together:
HTMLInputElement: Providesinputspecified properties-
HTMLElement: It provides commonly used HTML element methods (getterandsetter) Element: Provides common methods for elementsNode: Provides public DOM node attributesEventTarget: Provide support for events (override)Finally it inherits the methods of
Object(pure objects), such ashasOwnProperty
If we want to check the DOM node class name, we can use the commonly used constructor attribute of the object. It refers to the class constructor, and its name can be obtained using constructor.name. For example:

Or use toString to string it together, for example:

We also Inheritance can be checked using instanceof:

As we can see, DOM nodes are regular JavaScript objects. They use prototype-based classes for inheritance.
It's also easy to output elements in the browser using console.dir(elem). You can see HTMLElement.prototype, Element.prototype, etc. in the console.

DOM node type
In the section on browsers and DOM, we know that the browser will parse the HTML document into a series of nodes based on the DOM model, and then use These nodes form a DOM tree. The smallest component unit in DOM is called node (Node) , and the DOM tree is composed of 12 types of nodes.
Node in DOM has at least three basic attributes:
nodeType,nodeNameandnodeValue. The values of these three attributes will be different depending on the node type.
nodeType: This property returns the constant value of the node type. Different types correspond to different constant values. The 12 types correspond to constant values from1to12, as shown in the table belownodeName: This property returns the name of the nodenodeValue: This property returns Or set the value of the current node in the format of string
nodeTypeNode type:

And among them element node,text node and Attribute nodes are the most common node types we use to operate DOM.
In JavaScript, we can use instanceof and other class-based tests to see the node type, but sometimes nodeType may be simpler .

And nodeType is an attribute only, we cannot modify it.

DOM node tag
As mentioned earliernodeName will return the node name (the HTML tag is returned and is in uppercase of). That is to say, for a given DOM node, its tag name can be read through the nodeName attribute, such as:
document.body.nodeName // => BODY
In addition to the nodeName attribute, you can also Read through the tagName attribute:
document.body.tagName // => BODY
Although both nodeName and tagName can read the element tag name, but between the two Is there a difference? Of course, there are slight differences between the two:
tagName属性只能用于元素节点(Element)nodeName属性可以用于任意节点(Node)上,如果用于元素上,那么和tagName相同,如果用于其他节点类型,比如文本、注释节点等,它有一个带有节点类型的字符串
也就是说,tagName只支持元素节点(因为它源于Element类),而nodeName可以用于所有节点类型。比如下面这个示例,来比较一下tagName和nodeName的结果:

如果我们只处理DOM元素,那么我们就可以选择tagName属性来做相应的处理。
除了XHTML,标签名始终是大写的。浏览器有两种处理文档的模式:HTML和XML。通常HTML模式用于Web页面。当浏览器接收到一个带有
Content-Type:application/xml+xhtml的头,就会启用XML模式。在HTML模式中,tagName或者nodeName总是返回大写标签,比如或返回的是BODY;对于XML模式,现在很少使用了。
DOM节点内容
对于DOM节点的内容,JavaScript中提供了几个方法来对其进行操作,比如innerHTML、outerHTML、textContent、innerText、outerText和nodeValue等。接下来,咱们看看他们的使用场景以及相应的差异性。
为了易于帮助大家理解和掌握这向方法的使用,接下来的示例都将围绕着下面这个DOM结构来做处理:
<body> <!-- 主内容 --> <div id="main"> <p>The paragraph element</p> <div>The div </div> <input type="text" id="name" value="User name" /> </div> </body>
innerHTML
innerHTML属性允许我们获取元素的HTML,而且其获取的的值是一个String类型。比如:
let ele = document.getElementById('main') let eleContent = ele.innerHTML; console.log(typeof eleContent, eleContent)
输出的结果如下:

上面看到的是innerHTML属性获取某个元素的内容,当然innerHTML也可以修改某个元素的内容。比如:
let eleP = document.querySelector('p') eleP.innerHTML = '我是一个段落,新修改的内容:<a href="#">我是一个链接</a>'
刷新页面,段落p元素整个内容都将被修改了:

如果使用
innerHTML将<script></script>标签插入到document,它不会被执行。
使用innerHTML可以使用ele.innerHTML += "something"来追回更多的HTML,比如下面这个示例:
let eleP = document.querySelector('p') eleP.innerHTML += '我是一个段落,新修改的内容:' eleP.innerHTML += '<a href="#">我是一个链接</a>'
结果如下:

使用innerHTML要非常小心,因为它做的不是加法,而是完整的覆盖。还有:
当内容为“零输出”(zeroed-out)和从头重写时,所有的图像和其他资源将被重新加载。
outerHTML
outerHTML属性包含元素的全部HTML。就像innerHTML的内容加上元素本身一样。从文字难于理解或想象的话,咱们把上面的示例修改一下,通过innerHTML和outerHTML的结果来看其获取的是什么:
let eleP = document.querySelector('p') let eleInner = eleP.innerHTML let eleOuter = eleP.outerHTML console.log('>>> innerHTML >>>', eleInner) console.log('>>> outerHTML >>>', eleOuter)
输出的结果:

outerHTML和innerHTML也可以写入,但不同的是:
innerHTML可以写入内容,改变元素,但outerHTML在外部环境中取代了整体!
比如下面这个示例:
let eleP = document.querySelector('p') eleP.outerHTML = '<div class="new">把整个p元素换成div元素</div>'

从效果和页面源码上截图可以看出来,p替换了p。
outerHTML赋值不修改DOM元素,而是从外部环境中提取它,并插入一个新的HTML片段,而不是它。新手时常在这里会犯错误:修改eleP.outerHTML,然后继续使用eleP,就好像它有新的内容一样。
let eleP = document.querySelector('p') eleP.outerHTML = '<div class="new">把整个p元素换成div元素</div>' console.log(eleP.innerHTML)

我们可以写入outerHTML,但是要记住,它不会改变我们写入的元素。相反,它会在它的位置上创建新的内容。我们可以通过查询DOM获得对新元素的引用。比如:
let eleP = document.querySelector('p') eleP.outerHTML = '<div class="new">把整个p元素换成div元素</div>' console.log('>>>> ', eleP) let newEle = document.querySelector('.new') console.log('>>>> ', newEle)结果如下:

textContent
textContent属性和innerHTML以及outerHTML都不一样。textContent只获取元素的纯文本内容,包括其后代元素的内容。比如:
let mainEle = document.querySelector('#main') console.log('>>>> innerHTML >>>>', mainEle.innerHTML) console.log('>>>> outerHTML >>>>', mainEle.outerHTML) console.log('>>>> textContent >>>>', mainEle.textContent)
结果如下:

正如我们所看到的,textContent返回的只有文本内容,就像是把所有HTML元素的标签都删除了,但是它们的文本仍然保留着。正如上面示例中的,innerHTML、outerHTML和textContent输出的结果,可以一目了然知道他们之间的差异性。
textContent和其他两个属性一样,也可以写入内容。但对于textContent的写入更为有用,因为它写入的内容是纯内容,是一种安全方式。而innerHTML和outerHTML都会写入HTML,而会写入HTML标签的方式是一种不安全的形式,容易引起Web的XSS攻击。
XSS我们先忽略,来看看写入的差异性:
let mainEle = document.querySelector('#main') let content = "我要新内容,并带有一个标签:<b>Boo,Waa!!!</b>" mainEle.textContent = content mainEle.innerHTML = content mainEle.outerHTML = content
效果如下:

如果你够仔细的话,会发现,name中的<b>Boo,Waa!!!</b>的标签也被当做文本内容写进去了。如下图所示:

大多数情况之下,我们希望从用户那里得到文本,并希望将其视为文本。我们不希望在我们的网站上出现意想不到的HTML,那么textContent就可以得到你想要的。
innerText和outerText
innerText和outerText是IE的私有属性,获取的也是元素的文本内容,有点类似于textContent。所以这里只简单的提一提,并不深入展开。如果这里有误,请大大们指正。
nodeValue和data
innerHTML属性仅对元素节点有效。
其他节点类型有对应的节点:nodeValue和data属性。这两种方法在实际应用中几乎是相同的,只有很小的差异。来看看示例。
<body> Hello JavaScript!!!! <!-- 主内容 --> <div id="main"> <p>The paragraph element</p> <div>The div </div> <input type="text" id="name" value="User name" /> </div> <script> console.log('>>> nodeValue >>>', document.body.firstChild.nodeValue) console.log('>>> data >>>', document.body.firstChild.data) </script> </body>
他们输出的结果是相同的:

总结
每个DOM节点属于某个类。这些类构成一个DOM树。所有的属性和方法都将被继承。主要的DOM节点属性有:
nodeType:我们可以从DOM对象类中获取nodeType。我们通常需要查看它是否是文本或元素节点,使用nodeType属性很好。它可以获取对应的常数值,其中1表示元素节点,3表示文本节点。另外,该属性是一个只读属性。nodeName / tagName:tagName只用于元素节点,对于非元素节点使用nodeName来描述。它们也是只读属性。innerHTML:获取HTML元素的内容(包括元素标签自身)。其可以被修改。outerHTML:获取元素完整的HTML。outerHTML并没有触及元素自身。相反,它被外部环境中的新HTML所取代。nodeValue / data:非元素节点的内容(文本、注释)。这两个几乎是一样的,不过我们通常使用data。textContent:获取元素内容的文本,基本上是HTML减去所有的标签。它也具有写入特性,可以将文本放入元素中,所有特殊的字符和标记都被精确的处理为文本。
DOM节点也有其他属性,这取决于它们的类。例如,<input>元素(HTMLElement)具有value、type属性,而<a></a>元素(HTMLAnchorElement)具有href属性。大多数标准的HTML属性都具有相应的DOM属性。
【相关推荐:javascript视频教程、web前端】
The above is the detailed content of Summarize and share knowledge points about DOM node attributes. For more information, please follow other related articles on the PHP Chinese website!
Python vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AMPython 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.
From C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AMThe shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
JavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AMDifferent JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.
Beyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AMJavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AMI built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing
How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AMThis article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base
JavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AMJavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.
The Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AMThe latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

Notepad++7.3.1
Easy-to-use and free code editor

Atom editor mac version download
The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.







