JavaScript 代码动态添加新元素
JavaScript是学习浏览器工作原理时非常重要的一种语言。通常我们希望向网页中添加动态元素/内容。本文将介绍有关这方面的全部内容。
创建新元素: 可以通过使用 createElement() 方法在JS中创建新元素。
语法:
document.createElement("<tagName>");
// Where <tagName> can be any HTML
// tagName like div, ul, button, etc.
// newDiv element has been created
For Eg: **let newDiv = document.createElement("div");**
一旦元素被创建,让我们继续设置新创建元素的属性。
设置创建元素的属性: 可以使用 setAttribute() 方法来设置属性。
语法和示例如下:
Element.setAttribute(name, value);
// Where Element is the name of web element.
// Here, we have created newDiv.
// Where name is the attribute name and
// value is the value that needs to be set
For Eg: **newDiv.setAttribute("class","container");**
示例: 可以根据某些事件(比如点击)创建元素。以下是使用onclick事件动态创建元素的示例。该代码可以进一步扩展为一个待办事项列表!
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<style>
html,
body {
height: 100%;
width: 100%;
}
.button {
display: flex;
align-items: center;
justify-content: center;
}
.tasks {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
margin-top: 20px;
}
</style>
</head>
<body>
<div class="button">
<button id="addTask">Add task</button>
</div>
<div class="tasks"></div>
<script type="text/javascript">
// Getting the parent element in which
// the new div will be created
let task = document.getElementsByClassName("tasks");
// Getting the addTask button element
let addTask = document.getElementById("addTask");
// Adding onclick event to the button
addTask.addEventListener('click', function () {
// Traversing through collection of HTML
// elements (tasks here)
for (let i = 0; i < task.length; i++) {
// New div element is created
let newDiv = document.createElement("div");
// Setting the attribute of class type to newDiv
newDiv.setAttribute("class", "list");
// innerText used to write the text in newDiv
newDiv.innerText = "New Div created";
// Finally append the newDiv to the
// parent i.e. tasks
task[i].append(newDiv);
}
})
</script>
</body>
</html>
输出:

极客教程