ZetCode

JavaScript createElement

最后修改于 2025 年 4 月 2 日

在本文中,我们将探讨 JavaScript 中的 document.createElement 方法。此方法对于动态 DOM 操作至关重要,允许开发人员以编程方式创建新元素。

基本定义

document.createElement 方法创建由 tagName 指定的 HTML 元素。创建的元素不会自动添加到文档中;您必须显式将其附加到 DOM 树。

此方法返回一个新 HTML 元素,该元素可以在插入页面之前通过属性和特性进行修改。它是动态网页内容生成的根本工具。

创建简单元素

此示例演示了如何创建基本段落元素并将其添加到文档正文。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Basic createElement</title>
</head>
<body>

<script>
    // Create a new paragraph element
    const para = document.createElement('p');
    
    // Add text content to the paragraph
    para.textContent = 'This is a dynamically created paragraph.';
    
    // Append the paragraph to the document body
    document.body.appendChild(para);
</script>

</body>
</html>

在此基本示例中,我们使用 document.createElement('p') 创建了一个段落元素。然后,我们设置其文本内容并将其附加到文档正文。

这演示了创建元素的三个基本步骤:创建、配置和插入。在附加到 DOM 之前,元素存在于内存中。

创建带属性的元素

此示例展示了如何在将元素添加到文档之前创建它并设置属性。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Element with Attributes</title>
</head>
<body>

<div id="container"></div>

<script>
    // Create a new link element
    const link = document.createElement('a');
    
    // Set multiple attributes
    link.href = 'https://example.com';
    link.textContent = 'Visit Example.com';
    link.target = '_blank';
    link.className = 'external-link';
    
    // Append to container div
    document.getElementById('container').appendChild(link);
</script>

</body>
</html>

在这里,我们创建了一个锚点元素并设置了几个属性,包括 href、target 和 className。然后将该元素添加到特定的容器 div 中。

这演示了如何在插入之前使用各种属性配置元素。可以直接赋值属性,也可以使用 setAttribute。

创建嵌套元素

此示例演示了如何创建包含嵌套元素的更复杂结构。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Nested Elements</title>
</head>
<body>

<script>
    // Create a div container
    const div = document.createElement('div');
    div.className = 'card';
    
    // Create a heading
    const heading = document.createElement('h2');
    heading.textContent = 'Product Card';
    
    // Create a paragraph
    const para = document.createElement('p');
    para.textContent = 'This is a product description.';
    
    // Create a button
    const button = document.createElement('button');
    button.textContent = 'Add to Cart';
    
    // Build the nested structure
    div.appendChild(heading);
    div.appendChild(para);
    div.appendChild(button);
    
    // Add to document
    document.body.appendChild(div);
</script>

</body>
</html>

在此示例中,我们创建了多个元素并将它们嵌套起来,形成一个卡片组件。在将元素添加到文档之前,将它们组装起来。

这表明了如何以编程方式构建复杂的 DOM 结构。附加的顺序决定了文档中最终的嵌套结构。

创建带事件监听器的元素

此示例展示了如何创建元素并为其附加事件监听器。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Element with Event</title>
</head>
<body>

<div id="output"></div>

<script>
    // Create a button element
    const button = document.createElement('button');
    button.textContent = 'Click Me';
    
    // Add event listener
    button.addEventListener('click', function() {
        const output = document.getElementById('output');
        output.textContent = 'Button was clicked!';
    });
    
    // Add to document
    document.body.appendChild(button);
</script>

</body>
</html>

在这里,我们在将按钮元素添加到文档之前创建了它并为其附加了一个点击事件监听器。点击时,该监听器会更新另一个元素。

这演示了如何使动态元素具有交互性。可以随时添加事件监听器,可以在创建时添加,也可以根据需要稍后添加。

创建表单元素

此示例演示了如何创建包含多个输入元素的完整表单。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Dynamic Form</title>
</head>
<body>

<script>
    // Create form element
    const form = document.createElement('form');
    form.id = 'login-form';
    
    // Create username input
    const usernameLabel = document.createElement('label');
    usernameLabel.textContent = 'Username:';
    usernameLabel.htmlFor = 'username';
    
    const usernameInput = document.createElement('input');
    usernameInput.type = 'text';
    usernameInput.id = 'username';
    usernameInput.name = 'username';
    usernameInput.required = true;
    
    // Create password input
    const passwordLabel = document.createElement('label');
    passwordLabel.textContent = 'Password:';
    passwordLabel.htmlFor = 'password';
    
    const passwordInput = document.createElement('input');
    passwordInput.type = 'password';
    passwordInput.id = 'password';
    passwordInput.name = 'password';
    passwordInput.required = true;
    
    // Create submit button
    const submitButton = document.createElement('button');
    submitButton.type = 'submit';
    submitButton.textContent = 'Login';
    
    // Build form structure
    form.appendChild(usernameLabel);
    form.appendChild(usernameInput);
    form.appendChild(document.createElement('br'));
    form.appendChild(passwordLabel);
    form.appendChild(passwordInput);
    form.appendChild(document.createElement('br'));
    form.appendChild(submitButton);
    
    // Add form to document
    document.body.appendChild(form);
</script>

</body>
</html>

此示例创建了一个完整的登录表单,包含标签、输入框和提交按钮。所有元素均以编程方式创建和配置。

它演示了如何动态构建复杂的交互式表单。每个表单元素都以适当的属性创建,以确保其正常运行。

来源

MDN createElement 文档

在本文中,我们展示了如何在 JavaScript 中使用 document.createElement。此方法对于 Web 开发中的动态 DOM 操作和内容生成至关重要。

作者

我叫 Jan Bodnar,我是一名充满热情的程序员,拥有丰富的编程经验。我自 2007 年以来一直在撰写编程文章。至今,我已撰写了 1400 多篇文章和 8 本电子书。我在教授编程方面拥有十多年的经验。

列出 所有 JS DOM 教程