search
HomeWeb Front-endFront-end Q&AHow to modify DOM nodes using JavaScript

With the development of web applications, JavaScript has become an integral part. JavaScript can be used to modify web content and achieve dynamic effects. Among them, modifying the DOM is a very important part because it is the key to interacting with the web page.

What is DOM?
DOM is the Document Object Model, which is a tree structure representation of an HTML document. In this document, each HTML element is a node, such as: ,

,

, etc. These nodes can have child nodes and attributes. For example, the node

can contain child nodes , and it can also have attributes, such as class, id, etc. JavaScript changes the content of the web page by manipulating these nodes.

How to select nodes?
To manipulate the DOM, we need to select nodes. This can be achieved in a variety of ways, mainly the following methods:

  1. Select nodes by id

Use the document.getElementById() method to select nodes based on the specified id Select a node. As shown below:

var myNode = document.getElementById("myNode");

The above code will select an HTML element with id="myNode".

  1. Select nodes by class

To select one or more nodes with the same class attribute, you can use the getElementsByClassName() method. As shown below:

var myNodes = document.getElementsByClassName("classNode");

The above code will select all HTML elements whose class attribute is equal to "classNode".

  1. Select nodes by tag name

To select all nodes with specified tag names, you can use the getElementsByTagName() method. As shown below:

var myNodes = document.getElementsByTagName("p");

The above code will select all

tags in the document.

Operation of DOM node attributes
DOM nodes have many attributes, such as: id, class, title, etc. We can modify or get the values ​​of these properties through JavaScript. The following are some commonly used DOM node attribute manipulation methods:

  1. Get or set the innerHTML attribute

You can use the getInnerHTML() method to get the innerHTML attribute of the node. You can also use the setInnerHTML() method to set the innerHTML property of a node. As shown below:

var myNode = document.getElementById("myNode");

// 获取节点的innerHTML属性
var myNodeInnerHTML = myNode.innerHTML;

// 设置节点的innerHTML属性
myNode.innerHTML = "新的HTML内容";
  1. Get or set the innerText property

Get the innerText property using the getInnerText() method, and set the innerText property using the setInnerText() method. As shown below:

var myNode = document.getElementById("myNode");

// 获取节点的innerText属性
var myNodeInnerText = myNode.innerText;

// 设置节点的innerText属性
myNode.innerText = "新的文本内容";
  1. Get or set the nodeType attribute

The nodeType attribute returns the type of the current node. You can use the getNodeType() method to get the nodeType attribute of the node. You can also use the setNodeType() method to set the nodeType attribute of a node. As shown below:

var myNode = document.getElementById("myNode");

// 获取节点的nodeType属性
var myNodeType = myNode.nodeType;

// 设置节点的nodeType属性
myNode.nodeType = 1;
  1. Get or set the nodeName attribute

The nodeName attribute returns the name of the node. You can use the getnodeName() method to get the nodeName attribute of the node. You can also use the setnodeName() method to set the nodeName attribute of a node. As shown below:

var myNode = document.getElementById("myNode");

// 获取节点的nodeName属性
var myNodeName = myNode.nodeName;

// 设置节点的nodeName属性
myNode.nodeName = "span";
  1. Get or set the nodeValue property

The nodeValue property returns or sets the value of the node. The nodeValue property can be obtained using the getNodeValue() method. To set the property value, use the setNodeValue() method. As shown below:

var myNode = document.getElementById("myNode");

// 获取节点的nodeValue属性
var myNodeValue = myNode.nodeValue;

// 设置节点的nodeValue属性
myNode.nodeValue = "新的节点内容";
  1. Get or set the className attribute

The className attribute returns or sets the class name of the node. The className attribute can be obtained using the getclassName() method. To set the attribute value you can use the setclassName() method. As shown below:

var myNode = document.getElementById("myNode");

// 获取节点的className属性
var myClassName = myNode.className;

// 设置节点的className属性
myNode.className = "newClass";
  1. Get or set the id attribute

The id attribute returns or sets the id of the node. The id attribute can be obtained using the getId() method. To set the attribute value you can use the setId() method. As shown below:

var myNode = document.getElementById("myNode");

// 获取节点的id属性
var myId = myNode.id;

// 设置节点的id属性
myNode.id = "newNode";

Creation and insertion of DOM nodes
In addition to modifying DOM node attributes, DOM nodes can also be created and inserted into the existing DOM structure.

Create DOM node
To create a DOM node, you can use the createElement() method. As shown below:

// 创建一个新的 <p> 元素
var newNode = document.createElement("p");

// 设置元素的内容
newNode.innerHTML = "新的 HTML 内容";

// 将新元素添加到文档中
document.body.appendChild(newNode);</p>

Insert DOM node
There are the following points to insert DOM node:

  1. Insert parent node
    Use the appendChild() method to add elements to the end of the parent node. As shown below:
var parent = document.getElementById("parent");

// 创建新的 
  •  元素 var newNode = document.createElement("li"); // 设置元素的内容 newNode.innerHTML = "新的列表项"; // 将新元素添加到父节点的末尾 parent.appendChild(newNode);
    1. Insert sibling node
      Use the insertBefore() method to insert a new node before another node. As shown below:
    var newNode = document.createElement("li");
    
    // 设置元素的内容
    newNode.innerHTML = "新的列表项";
    
    // 将新元素添加到 "node" 元素之前
    parent.insertBefore(newNode, node);
    1. Replace Node
      Use the replaceChild() method to replace a node. As shown below:
    var newNode = document.createElement("li");
    
    // 设置元素的内容
    newNode.innerHTML = "新的列表项";
    
    // 替换父节点下的第二个子节点
    parent.replaceChild(newNode, parent.childNodes[1]);

    Removal of DOM nodes
    DOM nodes can be removed in a variety of ways. The following are some commonly used methods:

    1. Remove child nodes
      Use the removeChild() method to remove a child node. As shown below:
    var parent = document.getElementById("parent");
    
    // 移除 "node" 元素
    parent.removeChild(node);
    1. Remove itself
      Use the remove() method to remove the node itself. As shown below:
    var node = document.getElementById("node");
    
    // 移除节点本身
    node.remove();

    Summary
    By using JavaScript to manipulate the DOM, web page content, including HTML tags and text content, can be easily modified. We can select nodes, change node properties, create and insert new elements, and delete existing nodes. These operations allow the website to dynamically update and respond to user behavior.

  • The above is the detailed content of How to modify DOM nodes using JavaScript. For more information, please follow other related articles on the PHP Chinese website!

    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
    The Benefits of React: Performance, Reusability, and MoreThe Benefits of React: Performance, Reusability, and MoreApr 15, 2025 am 12:05 AM

    React’s popularity includes its performance optimization, component reuse and a rich ecosystem. 1. Performance optimization achieves efficient updates through virtual DOM and diffing mechanisms. 2. Component Reuse Reduces duplicate code by reusable components. 3. Rich ecosystem and one-way data flow enhance the development experience.

    React: Creating Dynamic and Interactive User InterfacesReact: Creating Dynamic and Interactive User InterfacesApr 14, 2025 am 12:08 AM

    React is the tool of choice for building dynamic and interactive user interfaces. 1) Componentization and JSX make UI splitting and reusing simple. 2) State management is implemented through the useState hook to trigger UI updates. 3) The event processing mechanism responds to user interaction and improves user experience.

    React vs. Backend Frameworks: A ComparisonReact vs. Backend Frameworks: A ComparisonApr 13, 2025 am 12:06 AM

    React is a front-end framework for building user interfaces; a back-end framework is used to build server-side applications. React provides componentized and efficient UI updates, and the backend framework provides a complete backend service solution. When choosing a technology stack, project requirements, team skills, and scalability should be considered.

    HTML and React: The Relationship Between Markup and ComponentsHTML and React: The Relationship Between Markup and ComponentsApr 12, 2025 am 12:03 AM

    The relationship between HTML and React is the core of front-end development, and they jointly build the user interface of modern web applications. 1) HTML defines the content structure and semantics, and React builds a dynamic interface through componentization. 2) React components use JSX syntax to embed HTML to achieve intelligent rendering. 3) Component life cycle manages HTML rendering and updates dynamically according to state and attributes. 4) Use components to optimize HTML structure and improve maintainability. 5) Performance optimization includes avoiding unnecessary rendering, using key attributes, and keeping the component single responsibility.

    React and the Frontend: Building Interactive ExperiencesReact and the Frontend: Building Interactive ExperiencesApr 11, 2025 am 12:02 AM

    React is the preferred tool for building interactive front-end experiences. 1) React simplifies UI development through componentization and virtual DOM. 2) Components are divided into function components and class components. Function components are simpler and class components provide more life cycle methods. 3) The working principle of React relies on virtual DOM and reconciliation algorithm to improve performance. 4) State management uses useState or this.state, and life cycle methods such as componentDidMount are used for specific logic. 5) Basic usage includes creating components and managing state, and advanced usage involves custom hooks and performance optimization. 6) Common errors include improper status updates and performance issues, debugging skills include using ReactDevTools and Excellent

    React and the Frontend Stack: The Tools and TechnologiesReact and the Frontend Stack: The Tools and TechnologiesApr 10, 2025 am 09:34 AM

    React is a JavaScript library for building user interfaces, with its core components and state management. 1) Simplify UI development through componentization and state management. 2) The working principle includes reconciliation and rendering, and optimization can be implemented through React.memo and useMemo. 3) The basic usage is to create and render components, and the advanced usage includes using Hooks and ContextAPI. 4) Common errors such as improper status update, you can use ReactDevTools to debug. 5) Performance optimization includes using React.memo, virtualization lists and CodeSplitting, and keeping code readable and maintainable is best practice.

    React's Role in HTML: Enhancing User ExperienceReact's Role in HTML: Enhancing User ExperienceApr 09, 2025 am 12:11 AM

    React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

    React Components: Creating Reusable Elements in HTMLReact Components: Creating Reusable Elements in HTMLApr 08, 2025 pm 05:53 PM

    React components can be defined by functions or classes, encapsulating UI logic and accepting input data through props. 1) Define components: Use functions or classes to return React elements. 2) Rendering component: React calls render method or executes function component. 3) Multiplexing components: pass data through props to build a complex UI. The lifecycle approach of components allows logic to be executed at different stages, improving development efficiency and code maintainability.

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

    Hot Tools

    SAP NetWeaver Server Adapter for Eclipse

    SAP NetWeaver Server Adapter for Eclipse

    Integrate Eclipse with SAP NetWeaver application server.

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    SublimeText3 English version

    SublimeText3 English version

    Recommended: Win version, supports code prompts!

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Dreamweaver Mac version

    Dreamweaver Mac version

    Visual web development tools