Home > Article > Web Front-end > How to replace page elements with javascript
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)" ".
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>
[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!