Welcome to the DOM Operations Guide! This guide will help you understand how to manipulate the Document Object Model (DOM) in your web development projects. Below, you'll find a list of common DOM operations along with examples.

常见 DOM 操作

获取元素

  • 使用 getElementById() 获取单个元素

    const element = document.getElementById('elementId');
    
  • 使用 getElementsByClassName() 获取所有具有特定类的元素

    const elements = document.getElementsByClassName('className');
    
  • 使用 getElementsByTagName() 获取所有具有特定标签名的元素

    const elements = document.getElementsByTagName('tagName');
    

更新内容

  • 使用 innerHTML 设置元素的 HTML 内容

    element.innerHTML = '<p>New content</p>';
    
  • 使用 textContent 设置元素的文本内容

    element.textContent = 'New text content';
    

添加元素

  • 使用 createElement() 创建新的元素

    const newElement = document.createElement('div');
    
  • 使用 appendChild() 将新元素添加到父元素中

    parent.appendChild(newElement);
    

删除元素

  • 使用 removeChild() 删除元素
    parent.removeChild(element);
    

代码示例

Below is an example of how you can use some of the DOM operations mentioned above:

// 获取元素
const element = document.getElementById('example');

// 更新内容
element.innerHTML = '<p>This is some new content.</p>';

// 创建新元素
const newElement = document.createElement('div');

// 设置新元素的文本内容
newElement.textContent = 'This is a new element!';

// 将新元素添加到父元素中
element.appendChild(newElement);

For more information and examples, please refer to our JavaScript Guide.

图片示例

HTML5 Logo