JavaScript 如何将HTML代码添加到div中
在本文中,我们将使用JavaScript将HTML代码添加到div元素中。为了做到这一点,我们首先使用document.getElementById()方法选择div元素,然后我们将使用下面提到的方法将HTML代码追加到div中。
有两种通过JavaScript将HTML代码追加到div中的方法:
- 使用innerHTML属性
- 使用insertAdjacentHTML()方法
方法1:使用innerHTML属性
要使用innerHTML属性追加内容,首先选择要追加代码的元素(div)。然后,使用+=运算符将代码作为字符串添加到innerHTML中。
语法:
element.innerHTML += "additional HTML code"
// OR
element.innerHTML = element.innerHTML +
"additional HTML code"
示例: 此示例使用上述解释的方法,使用JavaScript将HTML代码追加到div中。
<!DOCTYPE html>
<html>
<head>
<title>
How to Append HTML Code to
a Div using Javascript?
</title>
<style>
body {
text-align: center;
padding: 5%;
}
h1 {
color: green;
}
</style>
</head>
<body>
<div id="add_to_me">
<h1>GeeksforGeeks</h1>
<p>
This is the text which has
already been typed into
the div
</p>
</div>
<button onclick="addCode()">
Add Stuff
</button>
<script>
function addCode() {
document.getElementById("add_to_me")
.innerHTML +=
"<h3>This is the text which has been inserted by JS</h3>";
}
</script>
</body>
</html>
输出:
注意: 这个方法基本上会销毁div的所有内容并重新创建。因此,如果你在div的子节点上添加了监听器,它们将会丢失。
方法2:使用insertAdjacentHTML()方法
可以使用insertAdjacentHTML()方法将HTML代码追加到div元素中。但是,你需要选择div内的一个元素来添加代码。该方法有两个参数:
- 你希望插入代码的位置(在文件中)(’afterbegin’,’beforebegin’,’afterend’,’beforeend’)
- 你想插入的HTML代码需要用引号括起来
语法:
elementInsideDiv.insertAdjacentHTML(
'afterend',
'additional HTML code'
);
<!DOCTYPE html>
<html>
<head>
<title>
How to Append HTML Code to
a Div using Javascript?
</title>
<style>
body {
text-align: center;
padding: 5%;
}
h1 {
color: green
}
</style>
</head>
<body>
<div id="add_to_me">
<h1>GeeksforGeeks</h1>
<p id="add_after_me">
This is the text which has
already been typed into
the div
</p>
</div>
<button onclick="addCode()">
Add Stuff
</button>
<script>
function addCode() {
document.getElementById("add_after_me")
.insertAdjacentHTML("afterend",
"<h3>This is the text which has been inserted by JS</h3>");
}
</script>
</body>
</html>
输出:
注意: 如果您从用户处以这种方式将HTML代码插入,会导致您的网站存在跨站点脚本攻击的安全漏洞。