search
HomeWeb Front-endJS TutorialOrganize common JavaScript operations on various types of elements in DOM_Basic knowledge

Node type
nodeType
The following are some important nodeType values:
1: element element
2: Attribute attr
3: Text text
8: Comments
9: Document document

nodeName,nodeValue

Node relationship
childNodes: Each node has a childNodes attribute, which stores a NodeList object

firstChild: equivalent to childNodes[0]

lastChild: equivalent to childNodes.length-1

At the same time, other nodes in the same list can be accessed by using the previousSibling and nextSibling properties of each node in the list.

Operation Node
appendChild()

The appendChild() method is used to add a node to the end of the childNodes list. After adding a node, the relationship pointers of the new node, parent node and previous last child node of childNodes will be updated accordingly.

insertBefore()
insertBefore() This method accepts two parameters: the node to be inserted and the node used as a reference.

// 插入后成为最后一个子节点
returnedNode = someNode.insertBefore(newNode,null);

// 插入后成为第一个节点
returnedNode = someNode.insertBefore(newNode,someNode.firstChild);

// 插入到最后一个子节点前面
returnedNode = someNode.insertBefore(newNode,someNode.lastChild);

repaceChild()
repaceChild() accepts two parameters, the node to be inserted and the node to be replaced

var returnedNode = someNode.replaceChild(newNode,someNode.firstChild);

removeChild()
Only remove nodes, not replace them.

var formerFirstChild = someNode.removeChild(someNode.firstChild);

cloneNode()

item 1
item 2
item 3

var deepList = myList.cloneNode(true);
console.log(deepList.length); // 3

var shallowList = myList.cloneNode(false);
console.log(shallowList.childNodes.length); //0

Document type

Document node has the following characteristics:

  • The value of nodeType is 9;
  • The value of nodeName is #document;
  • The value of nodeValue is null;
  • The value of parentNode is null;
  • The value of ownerDocument is null;

Child node of document

var html = document.documentElement; // 取得对<html>的引用
console.log(html === document.childNodes[0]); // true
console.log(html === document.firstChild); // true

Document information

// 取得文档的标题
var originalTitle = document.title; 

// 设置文档标题
document.title = "New page title";

// 取得完整的url
var url = document.URL;
// 取得域名
var domain = document.domain;
// 取得来源页面的url
var referrer = document.referrer;

//假设页面来自p2p.wrox.com域
document.domain = "wrox.com"; // 成功
document.domain = "nczonline.net"; // 失败

Calling document.getElementById("myElement"); in IE7 will return the element as shown below;
The best way is not to make the name attribute of the form field the same as the ID of other elements.

<input type="text" name="myElement" value="text field">
<div id="myElement">a div</div>

Special Collection

  • document.anchors, contains all a elements with name attribute in the document;
  • document.forms, contains all form elements in the document, which is the same as the result obtained by document.getElementsByTagName("form");
  • document.images, contains all img elements in the document, which is the same as the result obtained by document.getElementsByTagName("img");
  • document.links, contains all a elements with href attributes in the document;

Document writing

<html>
<head>
   <title>document.write() Example 3</title>
</head>
<body>
   <script type="text/javascript">
     document.write("<script type=\"text/javascript\" src=\"file.js\">") + "<\/script>");
   </script>
</body>
</html>

The string will not be used as the closing tag of the external script tag, so there will be no redundant content on the page.

Element type
Element node has the following characteristics:

  • The value of nodeType is 1;
  • The value of nodeName is the tag name of the element;
  • The value of nodeValue is null;
  • parentNode may be Document or Element;

To access the tag name of an element, you can use the nodeName attribute or the tagName attribute;

<div id="myDiv"></div>
var div = document.getElementById("myDiv");
console.log(div.tagName); // DIV
console.log(div.nodeName); // DIV


if (element.tagName=="div") { // 不能这样比较,很容易出错
}

if (element.tagName.toLowerCase =="div") { // 这样最好(适用于任何文档)
}

Acquire characteristics
There are three main DOM methods for operating attributes, namely getAttribute(), setAttribute(), and removeAttribute();
Note that the attribute name passed to getAttribute() is the same as the actual attribute name. It seems that if you want to get the attribute value of class, you should pass in "class" instead of "className".

var div = document.getElementById("myDiv");
console.log(div.getAttribute("class")); // bd

Create element
New elements can be created using the document.createElement() method.

Child node of element
Before performing an operation, it is usually necessary to check the nodeType attribute first, as shown in the following example:

for (var i=0; len = element.childNodes.length; i<len; i++){
  if (element.childNodes[i].nodeType ==1) {
    // 执行某些操作
  }
}

Text类型
Text节点具有以下特征:

  • nodeType的值为3;
  • nodeName的值为"#text";
  • nodeValue的值为节点所包含的文本;
  • parentNode是一个Element;

创建文本节点
可以使用document.createTextNode()创建新文本节点。

规范化文本节点
normalize()

分割文本节点
splitText()

Comment类型
comment节点具有下列特征:

  • nodeType的值为8;
  • nodeName的值为"#comment";
  • nodeValue的值是注释的内容;
  • parentNode可能是Document或Element;
  • 不支持(没有)子几点;

DOM操作技术
操作表格

 // 创建 table
var table = document.createElement("table");
table.border = 1;
table.width = "100%";

// 创建tbody
var tbody = document.createElement("tbody");
table.appendChild(tbody);

// 创建第一行
tbody.insertRow(0);
tbody.rows[0].insertCell(0);
tbody.rows[0].cells[0].appendChild(document.createTextNode("cell 1,1"));
tbody.rows[0].insertCell(1);
tbody.rows[0].cells[1].appendChild(document.createTextNode("cell 2,1"));


// 创建第二行
tbody.insertRow(01);
tbody.rows[1].insertCell(0);
tbody.rows[1].cells[0].appendChild(document.createTextNode("cell 1,2"));
tbody.rows[1].insertCell(1);
tbody.rows[1].cells[1].appendChild(document.createTextNode("cell 2,2"));

document.body.appendChild(table);

选择符API
querySelector()方法

// 取得body元素
var tbody = document.querySelector('body');

// 取得ID为"myDIV"的元素
var myDIV = document.querySelector("#myDiv");

// 取得类为"selected"的第一个元素
var selected = document.querySelector(".selected");

// 取得类为"button"的第一个图像元素
var img = document.body.querySelector("img.button");

querySelectorAll()方法

// 取得某<div>中的所有<em>元素(类似于getElementsByTagName("em"))
var ems = document.getElementById("myDiv").querySelectorAll("em");

// 取得类为"selected"的所有元素
var selecteds = document.querySelectorAll(".selected");

// 取得所有<p>元素中的所有<strong>元素
var strongs = document.querySelectorAll("p strong");

HTML5
与类相关的扩充
getElementsByClassName()方法:
该方法可以通过document对象及所有HTML元素调用该方法。

// 取得所有类中包含"username"和"current"的元素。类名的先后顺序无所谓
var allCurrentUsernames = document.getElementsByClassName("username current");

// 取得ID为"myDiv"的元素中带有类名"selected"的所有元素
var selected = document.getElementById("myDiv").getElementsByClassName("selected");

焦点管理

HTML5也添加了辅助管理DOM焦点的功能。首先就是document.activeElement属性,这个属性始终会引用DOM中当前获得了焦点的元素。

var button = document.getElementById("myButton");
button.focus();
alert(document.activeElement === button); // true

默认情况下,文档刚刚加载完成时,document.activeElement中保存的是document.body元素的引用。文档加载期间,docuemnt.activeElement的值为null。
另外就是新增了document.hasFocus()方法,这个方法用于确定文档是否获得了焦点。

var button = document.getElementById("myButton");
botton.focus();
alert(document.hasFocus()); // true

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
JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different 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 WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript'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)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I 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)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This 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 LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript 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 ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The 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.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

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

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

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.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools