Home > Web Front-end > JS Tutorial > body text

How to add a new element node in js? (Detailed explanation with pictures and text)

青灯夜游
Release: 2018-10-15 14:46:17
Original
5484 people have browsed it

How to add a new element node in js? This article will introduce to you how to add new nodes of elements in js. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

To add a new element node in js, you must first create a new element node, and then add the new element node to the html page. Below we use a simple code example to learn more about how JavaScript adds new nodes to elements.

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>js添加元素新节点</title>
		<style>
			#div{
				width: 200px;
				height: 150px;
				border: 2px solid red;
				margin: 50px auto;
				padding: 10px;
			}
		</style>
	</head>

	<body>
		<div id="div">
			<p id="p1">这是一个段落</p>
			<p id="p2">这是另一个段落</p>
		</div>

		<script>
			var para = document.createElement("p");
			var node = document.createTextNode("这是一个新的段落。");
			para.appendChild(node);

			var element = document.getElementById("div");
			element.appendChild(para);
		</script>
	</body>
</html>
Copy after login

Rendering:

How to add a new element node in js? (Detailed explanation with pictures and text)

Let’s analyze it:

1, document.createElement("p") Indicates the creation of a new p tag node (the third p tag);
document.createTextNode() Indicates the creation of a new text content node: this is a new paragraph.

2. Use para.appendChild(node);Add the created text content (node) to the created new p tag (node);
Use appendChild(para) to add (insert) the created p tag (node) and its content (node) into the box with id="div" and display it on the html page.

Summary: The above is the entire content of how to add new elements to js. I hope it will be helpful to everyone's learning. For more related tutorials, please visit JavaScript Video Tutorial, jQuery Video Tutorial, bootstrap Tutorial!

The above is the detailed content of How to add a new element node in js? (Detailed explanation with pictures and text). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!