DOM.JS

学习《DOM启蒙》一书,书中实例

"use strict";

(function(win){

	var global = win;

	var doc = global.document;



	var dom = function(params,context){

		return new GetOrMakeDom(params,context);

	}

	var regXContainTag = /^\s*<(\w+|!)[^>]*>/;

	var GetOrMakeDom = function(params,context){

		var currentContext = doc;

		if(context){
			if(context.nodeType){
				currentContext = context;
			}else{
				currentContext = doc.querySelector(context);
			}
			

		}

		if(!params || params ==='' || typeof params ==='string' && params.trim() ===''){

			this.length = 0;

			return this;
		}

		if(typeof params==='string' && regXContainTag.test(params)){
			var divEle = currentContext.createElement('div');
			divEle.className = 'hippo-doc-frag-wrapper';
			var docFrag = currentContext.createDocumentFragment();
			docFrag.appendChild(divEle);
			var queryDiv = currentContext.querySelector('div');
			queryDiv.innerHTML = params;
			var numberOfChildren = queryDiv.children.length;

			for(var z=0; z < numberOfChildren; z++){
				this[z] = queryDiv.children[z];
			}
			this.length = numberOfChildren;

			return this;
		}

		if(typeof params =='object' && params.nodeName){
			this[0] = params;

			this.length = 1;
			return this;
		}

		var nodes;

		if(typeof params !=='string'){
			nodes = params;
		}else{
			nodes = currentContext.querySelectorAll(params.trim());
		}

		var nodeLength = nodes.length;
		for(var i = 0; i< nodeLength; i++){
			this[i] = nodes[i]
		}
		this.length = nodeLength;

		return this;


	}

	global.dom = dom;

	dom.fn = dom.prototype;

	dom.fn = GetOrMakeDom.prototype;

	dom.fn.each = function(callback){

		var len  = this.length;

		for(var i=0; i< len; i++){
			callback.call(this[i],i,this[i]);
		}
		return this;

	}

	dom.fn.html=function(htmlString){

		if(htmlString){

			return this.each(function(){
				this.innerHTML = htmlString;
			})

		}else{
			return this[0].innerHTML;
		}
	}

	dom.fn.text=function(textString){

		if(textString){

			return this.each(function(){
				this.textContent = textString;
			})

		}else{
			return this[0].textContent.trim();
		}
	}

	dom.fn.append = function (stringObject){
		return this.each(function() {

			if(typeof stringObject==='string'){
				this.insertAdjacentHTML('beforeend',stringObject);
			}else{
				var that = this;
				dom(stringObject).each(function(name,value){
					that.insertAdjacentHTML('beforeend',value,name);
				})
			}
		})
	}

})(window)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值