JavaScript插入节点小结
JS原生API插入节点的方式大致有innerHTML、outerHTML、appendChild、insertBefore、insertAdjacentHTML、applyElement这6种。
这里总结一下各自的用法,并封装包含before、prepend、append、after、applyElement的一系列函数。
一、六种方式的用法
innerHTML:获取标签内部的HTML内容。
outerHTML:获取包括目标标签在内,以及内部HTML的内容。
appendChild:向目标标签末尾添加子节点,返回参数节点。
insertBefore:向目标节点的第二个参数位置添加第一个参数为子节点,返回第一个参数。
insertAdjacentHTML:向目标节点的指定位置添加节点;第二个参数为要添加的节点,第一个参数指定位置,位置包括beforebegin(添加为previousSibling)、afterbegin(添加为firstChild)、beforeend(添加为lastChild)、afterend(添加为nextSibling)。它还有两个兄弟函数,分别是insertAdjacentElement和insertAdjacentText,前者添加元素并返回该元素,后者添加文本。
applyElement:IE的函数,将参数节点设置成目标节点的外包围或者内包围;第一个为参数节点,第二个参数指定方式,方式包括inside(内包围,即参数节点将目标节点的子节点包起来)、outside(外包围,即参数节点将目标节点包起来)。
上面6种方式除了前两个是属性外,另外4个都是函数。innerHTML与outerHTML没有什么好说的,直接用HTML字符串赋值就能达到插入的目的了;appendChild简单套一层函数外壳就能封装成append函数;insertBefore让节点的插入方式非常灵活;insertAdjacentHTML可以实现字符串的插入方式;applyElement函数兼容一下即可成为JQuery的Wrap系列函数。
二、实现before、prepend、append、after函数
before把参数节点插入到目标节点前面,只需获取目标节点的父节点,然后父节点调用insertBefore即可。
prepend把参数节点插入到目标节点第一个子节点的位置,获取目标节点的第一个子节点,然后调用insertBefore即可。
append的功能和原生API里appendChild的功能一样。
after把参数节点插入到目标节点的后面,只需获取目标节点的nextSibling,然后调用insertBefore即可。
具体实现如下:
var append = function(node, scope) {
if(node.nodeType === 1 || node.nodeType === 9 || node.nodeType === 11) {
scope.appendChild(node);
}
};
var prepend = function(node, scope) {
if(node.nodeType === 1 || node.nodeType === 9 || node.nodeType === 11) {
scope.insertBefore(node, scope.firstChild);
}
};
var before = function(node, scope) {
if(node.nodeType === 1 || node.nodeType === 9 || node.nodeType === 11) {
scope.parentNode.insertBefore(node, scope);
}
};
var after = function(node, scope) {
if(node.nodeType === 1 || node.nodeType === 9 || node.nodeType === 11) {
scope.parentNode.insertBefore(node, scope.nextSibling);
}
};
上面函数只能插入元素节点、文档节点以及文档碎片,都是节点类型。如果我们想要支持字符串形式的插入方式,则需要封装insertAdjacentHTML了。
这里利用策略模式,将我要实现的四个函数做成策略对象,然后动态生成,以达到精简代码的效果:
//E5才有的迭代, 所以迭代要预先兼容
Array.prototype.forEach = [].forEach || function(callback) {
for(var i = 0, len = this.length; i < len; i++) {
callback.call(this[i], this[i], i, this);
}
}; /**插入策略集合**/
var insertStrategies = {
before : function(node, scope) {
scope.parentNode.insertBefore(node, scope);
},
prepend : function(node, scope) {
scope.insertBefore(node, scope.firstChild);
},
append : function(node, scope) {
scope.appendChild(node);
},
after : function(node, scope) {
scope.parentNode.insertBefore(node, scope.nextSibling);
}, /*支持字符串格式的插入, 注意:要兼容不可直接做div子类的元素*/
/*insertAdjace还有Element和Text,前者只能插元素,后者只能插文本*/
beforestr : function(node, scope) {
scope.insertAdjacentHTML('beforeBegin', node);
},
prependstr : function(node, scope) {
scope.insertAdjacentHTML('afterBegin', node);
},
appendstr : function(node, scope) {
scope.insertAdjacentHTML('beforeEnd', node);
},
afterstr : function(node, scope) {
scope.insertAdjacentHTML('afterEnd', node);
}
}; //响应函数
var returnMethod = function(method, node, scope) {
//如果是字符串
if(typeof node === 'string') {
return insertStrategies[method + 'str'](node, scope);
}
//1(元素)、9(文档)、11(文档碎片)
if(node.nodeType === 1 || node.nodeType === 9 || node.nodeType === 11) {
return insertStrategies[method](node, scope);
}
//此处还可添加节点集合的处理逻辑,用于处理选择其引擎获取的节点集合。
}; ['before', 'prepend', 'append', 'after'].forEach(function(method){
window[method] = function(node, scope) {
returnMethod(method, node, scope);
};
});
所有函数都被实现为window的属性,所以直接当全局函数调用即可,这些函数并不属于节点对象,所以scope参数指代的是目标节点。下面兼容applyElement后,我们将所有的函数都扩展到HTMLElement的原型上面去,这样就可以省略scope参数,以达到元素节点直接调用的效果。当然对于框架来说,一般是生成框架对象,然后把这些函数扩展到其原型上去,这样可以避免修改原生对象的原型。
三、兼容applyElement
applyElement函数是IE私有实现,所以想在其他浏览器中使用,我们得类似Array的forEach一样在对象原型上兼容一下。
其实要达到新元素包含目标节点或者包含目标元素的子节点用innerHTML与outerHTML也能做到。但是这必然会存在一个问题:当新元素是dom树的一部分,并且它也有一系列子节点,那么它的子节点应该怎么处理?留在原地还是并入目标元素中?如果并入目标元素中是目标元素的在前还是新元素的在前?
wrap系列函数效果只是挪走新元素标签里的内容,它的子元素呈现的效果就是变成新元素父节点点的子节点。这种方式也可以用Range对象来实现,当然也可以用innerHTML与outerHTML来实现。我这里用Range对象实现一遍。
/*兼容IE的applyElement*/
HTMLElement.prototype.removeNode = HTMLElement.prototype.removeNode || function(deep) {
if(this.parentNode) {
var range = this.ownerDocument.createRange();
range.selectNodeContents(this);
if(!deep) {
var fragment = range.extractContents();
range.setStartBefore(this);
range.insertNode(fragment);
range.detach();
}
return this.parentNode.removeChild(this);
}
}; HTMLElement.prototype.applyElement = HTMLElement.prototype.applyElement || function(node, where) {
node = node.removeNode();
where = (where || 'outside').toLowerCase();
var range = this.ownerDocument.createRange();
if(where === 'inside') {
range.selectNodeContents(this);
range.surroundContents(node);
range.detach();
}else if(where === 'outside') {
range.selectNode(this);
range.surroundContents(node);
range.detach();
}
return node;
};
四、将所有函数扩展到HTMLElement的原型上
思路和修复applyElement一样,我们只需将window[method]替换成HTMLElement.prototype[method],批量生成时传递的scope改成this即可达成。
//E5才有的迭代, 所以迭代要预先兼容
Array.prototype.forEach = [].forEach || function(callback) {
for(var i = 0, len = this.length; i < len; i++) {
callback.call(this[i], this[i], i, this);
}
}; /**插入策略集合**/
var insertStrategies = {
before : function(node, scope) {
scope.parentNode.insertBefore(node, scope);
},
prepend : function(node, scope) {
scope.insertBefore(node, scope.firstChild);
},
append : function(node, scope) {
scope.appendChild(node);
},
after : function(node, scope) {
scope.parentNode.insertBefore(node, scope.nextSibling);
}, /*支持字符串格式的插入, 注意:要兼容不可直接做div子类的元素*/
/*insertAdjace还有Element和Text,前者只能插元素,后者只能插文本*/
/**/
beforestr : function(node, scope) {
scope.insertAdjacentHTML('beforeBegin', node);
},
prependstr : function(node, scope) {
scope.insertAdjacentHTML('afterBegin', node);
},
appendstr : function(node, scope) {
scope.insertAdjacentHTML('beforeEnd', node);
},
afterstr : function(node, scope) {
scope.insertAdjacentHTML('afterEnd', node);
}
}; //响应函数
var returnMethod = function(method, node, scope) {
//如果是字符串
if(typeof node === 'string') {
//低版本浏览器使用机会毕竟少数,每次都要判断很划不来。这段代码舍弃
/*if(!scope.insertAdjacentHTML){
throw new Error('(Firefox8-、IE4-、Opera7-、Safari4-)浏览器不能插入字符串!');
}*/
return insertStrategies[method + 'str'](node, scope);
}
//1(元素)、2(属性)、3(文本)、9(文档)、11(文档碎片)
if(node.nodeType === 1 || node.nodeType === 9 || node.nodeType === 11) {
return insertStrategies[method](node, scope);
}
//此处还可添加节点集合的处理逻辑(用文档碎片)
}; ['before', 'prepend', 'append', 'after'].forEach(function(method){
HTMLElement.prototype[method] = function(node) {
returnMethod(method, node, this);
};
}); /*兼容IE的applyElement*/
HTMLElement.prototype.removeNode = HTMLElement.prototype.removeNode || function(deep) {
if(this.parentNode) {
var range = this.ownerDocument.createRange();
range.selectNodeContents(this);
if(!deep) {
var fragment = range.extractContents();
range.setStartBefore(this);
range.insertNode(fragment);
range.detach();
}
return this.parentNode.removeChild(this);
}
}; HTMLElement.prototype.applyElement = HTMLElement.prototype.applyElement || function(node, where) {
node = node.removeNode();
where = (where || 'outside').toLowerCase();
var range = this.ownerDocument.createRange();
if(where === 'inside') {
range.selectNodeContents(this);
range.surroundContents(node);
range.detach();
}else if(where === 'outside') {
range.selectNode(this);
range.surroundContents(node);
range.detach();
}
return node;
};
五、测试
测试代码如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>插入节点.html</title>
<script type="text/javascript" src='./insertNode.js'></script>
</head>
<body> <div id='div' style='background:#888;border:1px solid #888;padding:10px;'>坐标div</div>
<div id='inside' style='background:#0f0;border:1px solid #888;padding:10px;'>inside</div>
<div id='outside' style='background:#F00;border:1px solid #888;padding:10px;'>outside</div> <script type="text/javascript">
var div = document.getElementById('div'); var beforeDiv = document.createElement('div');
beforeDiv.innerHTML = 'beforeDiv';
beforeDiv.style.background = '#eee'; var prepEndDiv = document.createElement('div');
prepEndDiv.innerHTML = 'prepEndDiv';
prepEndDiv.style.background = '#ff0'; var appendDiv = document.createElement('div');
appendDiv.innerHTML = 'appendDiv';
appendDiv.style.background = '#0ff'; var afterDiv = document.createElement('div');
afterDiv.innerHTML = 'afterDiv';
afterDiv.style.background = '#f0f'; div.before(beforeDiv);
div.prepend(prepEndDiv);
div.append(appendDiv);
div.after(afterDiv); //测试文本插入
div.append('[我是乐小天,我来测试直接插入文本]'); //测试外包含和内包含
var outside = document.getElementById('outside');
var inside = document.getElementById('inside');
outside.applyElement(inside, 'inside');
</script>
</body>
</html>
结果图:

参考书目:《javascript框架设计》、《javascript高级程序设计》、《JavaScript设计模式与开发实践》
JavaScript插入节点小结的更多相关文章
- JS(JavaScript)插入节点的方法appendChild与insertBefore
首先 从定义来理解 这两个方法: appendChild() 方法:可向节点的子节点列表的末尾添加新的子节点.语法:appendChild(newchild) insertBefore() 方法:可在 ...
- JavaScript插入节点
1. document.write("<p>This is inserted.</p>"); 该方法必须加在HTML文档内,违背了结构行为分离原则,不推荐. ...
- JavaScript之节点的创建、替换、删除、插入
1.节点的创建 节点的创建使用document.creatElment();文本节点的创建使用document.creatTextNode();如想把<li>哈密瓜</li>添 ...
- javascript之DOM编程设置节点插入节点
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- javascript数据结构与算法--二叉树(插入节点、生成二叉树)
javascript数据结构与算法-- 插入节点.生成二叉树 二叉树中,相对较小的值保存在左节点上,较大的值保存在右节点中 /* *二叉树中,相对较小的值保存在左节点上,较大的值保存在右节点中 * * ...
- Javascript基础篇小结
转载请声明出处 博客原文 随手翻阅以前的学习笔记,顺便整理一下放在这里,方便自己复习,也希望你有也有帮助吧 第一课时 入门基础 知识点: 操作系统就是个应用程序 只要是应用程序都要占用物理内存 浏览器 ...
- JavaScript DOM节点和文档类型
以下的例子以此HTML文档结构为例: <!DOCTYPE html> <html lang="en"> <head> <meta char ...
- 用javascript插入样式
一.用javascript插入<style>样式 有时候我们需要利用js来动态生成页面上style标签中的css代码,方法很直接,就是直接创建一个style元素,然后设置style元素里面 ...
- JQuery_DOM 节点操作之创建节点、插入节点
一.创建节点 为了使页面更加智能化,有时我们想动态的在html 结构页面添加一个元素标签,那么在插入之前首先要做的动作就是:创建节点 <script type="text/javasc ...
随机推荐
- c#设计模式之观察者模式(Observer Pattern)
场景出发 一个月高风黑的晚上,突然传来了尖锐的猫叫,宁静被彻底打破,狗开始吠了,大人醒了,婴儿哭了,小偷跑了 这个过程,如果用面向对象语言来描述,简单莫过于下: public class Cat { ...
- cesium随笔 — 隐藏三维场景下方版权信息
上图中的版权信息相信很多人都想去掉,那么下面我将介绍一种简单粗暴的方法将其隐藏起来: .cesium-widget-credits { display: none!important; visibil ...
- WPF成长之路------翻转动画
先介绍一下RenderTransform类,该类成员如下: TranslateTransform:能够让某对象的位置发生平移变化. RotateTransform:能够让某对象产生旋转变化,根据中心点 ...
- Python 日常学习
习惯了java的思想.用java的思想来获取python元组中的数据.结果出错了. yuanzu_s = ("one", "two", "three& ...
- pageadmin CMS Sql Server2008 R2数据库安装教程
sql sever数据库建议安装sql2008或以上版本,如果电脑上没有安装数据库,参考下面步骤安装. sql2008 r2下载地址:点击下载 提取码: wfb4 下载后点击安装文件,安装步骤如下 ...
- iOS Keychain 跨应用
Keychain 可以用来持久保存一些信息.通常每个应用都有自己的 Keychain Access.但有时你会需要多个应用共用一些信息.这时需要创建 Keychain Access Group. Ke ...
- BZOJ1558 等差数列
题目链接:戳我 实话实话,看了几篇题解真的没看懂,我觉得讲的都有问题.这里对于线段树维护的s写了一点我自己的理解. 看到等差数列,我们考虑对数列做差,这样如果是等差数列,那么值应该相等.(比较容易维护 ...
- Jquery选择器 选择一个不存在的元素 为什么不会返回 false
不管找没找到,$()函数都会返回一个jquery对象,这个jquery对象有个length属性,表示找到多少个匹配的DOM元素,为0就是没找到.
- Utils工具方法集插件详解
var Utils = function(){}; Utils.text = { stripTags: function (val) { return val.replace(/<\/?[^&g ...
- How to manage local libraries in IntelliJ IDEA
如何在 IntelliJ IDEA 中管理本地类库 一般来说,如果项目是基于 Maven 管理工具的,我们会在 pom.xml 中添加 dependency 来管理依赖.但有时也会遇到要用的类库不在 ...