Home >Web Front-end >JS Tutorial >How to add p element in JavaScript

How to add p element in JavaScript

青灯夜游
青灯夜游Original
2022-02-08 14:36:394040browse

How to add p element in JavaScript: 1. Use the "document.createElement("p")" statement to create a new p element node; 2. Use the "parent node.appendChild(p element node)" statement Adds the newly created p node to the specified parent node.

How to add p element in JavaScript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

JavaScript adds p element

Implementation idea:

1. Use document.createElement() to create a node

2. Add the created node to the parent node using the parent Element.appendChild (child element) method

Implementation code:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<style>
			p{
				height: 20px;
				border: 1px solid red;
			}
		</style>
	</head>
	<body>

		<div id="div1">
			<p id="p1">这是一个段落。</p>
			<p id="p2">这是另一个段落。</p>
		</div>
		<button onclick="myFunction()">添加p元素</button>
		<script>
			function myFunction() {
				var para = document.createElement("p"); //创建新的<p> 元素
				var node = document.createTextNode("这是一个新段落。"); //创建文本节点
				para.appendChild(node); //向 <p> 元素追加这个文本节点 
				//向已有的元素追加这个新元素 
				var element=document.getElementById("div1"); 
				element.appendChild(para);
			}
		</script>
	</body>
</html>

How to add p element in JavaScript

【 Related recommendations: javascript learning tutorial

The above is the detailed content of How to add p element in 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