Home >Web Front-end >JS Tutorial >Can javascript add tags?

Can javascript add tags?

青灯夜游
青灯夜游Original
2022-01-19 11:02:203258browse

Javascript can add labels. Method: 1. Use the "document.createElement("label name")" statement to create a new label node; 2. Use the insertBefore() or appendChild() function before specifying the child element node. or insert a new label node afterwards.

Can javascript add tags?

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

There are two cases of node insertion: appending a child node after the element's child node list and inserting a child node in front of a child node of the element:

  • The first way Case call: element.appendChild (child node);

  • The second case call: element.insertBefore (new node, existing node).

Example 1:Append child nodes after the element child node list

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
	</head>
	<body>

		<ul id="myList">
			<li>Coffee</li>
			<li>Tea</li>
		</ul>
		<p id="demo">单击按钮将项目添加到列表中</p>
		<button onclick="myFunction()">点我</button>
		<script>
			function myFunction() {
				var node = document.createElement("LI");
				var textnode = document.createTextNode("Water");
				node.appendChild(textnode);
				document.getElementById("myList").appendChild(node);
			}
		</script>
	</body>
</html>

Can javascript add tags?

Note:

  • First create a node,

  • Then create a text node,

  • Then add the text node Add it to the LI node.

  • Finally add the node to the list.

Example 2: Insert a child node in front of a child node of the element

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
	</head>
	<body>

		<ul id="myList">
			<li>Coffee</li>
			<li>Tea</li>
		</ul>
		<p id="demo">单击按钮插入一个项目列表</p>
		<button onclick="myFunction()">点我</button>
		<script>
			function myFunction() {
				var newItem = document.createElement("LI")
				var textnode = document.createTextNode("Water")
				newItem.appendChild(textnode)
				var list = document.getElementById("myList")
				list.insertBefore(newItem, list.childNodes[0]);
			}
		</script>
	</body>
</html>

Can javascript add tags?

Note:

  • First create a li node,

  • Then create a text node,

  • Then add the text node in the li node.

  • Finally insert the li node into the first child node list.

[Related recommendations: javascript learning tutorial]

The above is the detailed content of Can javascript add tags?. 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