Home  >  Article  >  Web Front-end  >  How to replace page elements with javascript

How to replace page elements with javascript

青灯夜游
青灯夜游Original
2022-01-26 15:10:105861browse

In JavaScript, you can use the replaceChild() method to replace page elements. The function of this method is to replace a certain child node with a new node. The syntax is "parent node.replaceChild(new node, old node that needs to be replaced)" ".

How to replace page elements with javascript

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

In javascript, you can use the replaceChild() method to replace page elements.

replaceChild() method replaces a child node with a new node. This new node can be an existing node in the document, or you can create a new node.

Syntax:

node.replaceChild(newnode,oldnode)
Parameters Type Description
newnode Node object Required. The node object you wish to insert.
oldnode Node object Required. The node object you wish to delete.

Example:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
	</head>
	<body>
		<div><b id="oldnode">JavaScript</b>是一个很常用的技术,为网页添加动态效果。</div><br />
		<button onclick="replaceMessage()"> 将加粗改为斜体</a>

			<script type="text/javascript">
				function replaceMessage() {
					var oldNode = document.getElementById("oldnode"); //提取老元素;
					var newNode = document.createElement("i"); //创建一个新的节点;
					newNode.innerHTML = oldNode.innerHTML; //把旧的oldnode内容赋值给新的newnode,要不然newnode是无内容,只是简单的改了个属性,把b变成了i,显示出来的是空;
					oldNode.parentNode.replaceChild(newNode, oldNode); //实现子节点(对象)的替换,返回被替换对象的引用;
				}
			</script>

	</body>
</html>

How to replace page elements with javascript

[Related recommendations: javascript learning tutorial]

The above is the detailed content of How to replace page elements with 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