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

javascript替换已有元素replaceChild()使用介绍_javascript技巧

WBOY
Release: 2016-05-16 16:53:28
Original
1871 people have browsed it

replaceChild(a,b)是用来替换文档中的已有元素的
参数a:要插入的节点,
参数b:要替换的节点

复制代码 代码如下:

var oDiv = document.getElementById("guoDiv");
var oSpan = document.createElement("span");
oSpan.innerHTML = "4";
var firsChild = oDiv.firstElementChild ? oDiv.firstElementChild : oDiv.firstChild
var returnNode = oDiv.replaceChild(oSpan, firsChild); //替换第一个元素,返回被替换掉的元素
alert(returnNode.innerHTML); //1
var lastChild = oDiv.lastElementChild ? oDiv.lastElementChild : oDiv.lastChild;
oSpan = document.createElement("span");
oSpan.innerHTML = "5";
returnNode = oDiv.replaceChild(oSpan, lastChild); //替换最后一个,返回被替换掉的元素
alert(returnNode.innerHTML);//3

复制代码 代码如下:


1
2
3

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!