JavaScript DOM操作

DOM查询:

getElementById():Document对象,返回值类型是元素对象

getElementsByTagName():元素对象,返回值类型是类数组NodeList object。

getElementsByClassName():元素对象,返回值类型是类数组NodeList object。(IE8和IE8以下不支持)

由于getElementsByClassName()存在兼容性,getElementsByTagName()最常用。

querySelector() :元素对象,方法返回匹配指定CSS 选择器元素的第一个子元素对象(IE7和IE7以下不支持)

querySelectorAll():元素对象,返回匹配指定 CSS 选择器元素的所有子元素节点列表,也是类数组(IE7和IE7以下不支持)

API 只作用于 document 唯一返回值 live
getElementById  
getElementsByTagName  
getElementsByClassName    
querySelectorAll      
querySelector    
getElementsByClassName()兼容方法:

function getElementsByClassName(root, className) {
  // 特性侦测
  if (root.getElementsByClassName) {
    // 优先使用 W3C 规范接口
    return root.getElementsByClassName(className);
  } else {
    // 获取所有后代节点
    var elements = root.getElementsByTagName('*');
    var result = [];
    var element = null;
    var classNameStr = null;
    var flag = null;

    className = className.split(' ');

    // 选择包含 class 的元素
    for (var i = 0, element; element = elements[i]; i++) {
      classNameStr = ' ' + element.getAttribute('class') + ' ';
      flag = true;
      for (var j = 0, name; name = className[j]; j++) {
        if (classNameStr.indexOf(' ' + name + ' ') === -1) {
          flag = false;
          break;
        }
      }
      if (flag) {
        result.push(element);
      }
    }
    return result;
  }
}
遍历节点树:

element.parentNode
element.firstChild/element.lastChild
element.childNodes:子节点(儿子节点)
element.previousSibling/element.nextSibling
基于元素节点的遍历:

Node.parentElement:返回当前节点的父Element节点。如果当前节点没有父节点,或者父节点类型不是Element节点,则返回null。

children:返回一个动态的HTMLCollection集合,由当前节点的所有Element子节点组成。
firstElementChild:返回当前节点的第一个Element子节点,如果不存在任何Element子节点,则返回null
lastElementChild:返回当前节点的最后一个Element子节点,如果不存在任何Element子节点,则返回null。

nextElementSibling:返回下一个兄弟元素节点。

previousElementSibling:返回上一个兄弟元素节点。

children()实现:

function retElementChild(node){
	var temp = {
		length : 0,
		push : Array.prototype.push,
		splice : Array.prototype.splice
	},
	child = node.childNodes,
	len = child.length;
	for(var i = 0;i<len;i++){
		if(child[i].nodeType === 1){
			temp.push(child[i]);
		}
	}
	return temp;
}

节点的相关属性:

Node.nodeName,Node.nodeType

类型 nodeName nodeType
ELEMENT_NODE 大写的HTML元素名 1
ATTRIBUTE_NODE 等同于Attr.name 2
TEXT_NODE #text 3
COMMENT_NODE #comment 8
DOCUMENT_NODE #document 9
DOCUMENT_FRAGMENT_NODE #document-fragment 11
DOCUMENT_TYPE_NODE 等同于DocumentType.name 10
Node.nodeValue

返回一个字符串,表示当前节点本身的文本值,该属性可读写。由于只有Text节点、Comment节点、XML文档的CDATA节点有文本值,因此只有这三类节点的nodeValue可以返回结果,其他类型的节点一律返回null。

Node.attributes :

<div class="demo" id="only">
var div = document.getElementsByTagName('div')[0];
console.log(div.attributes);//NamedNodeMap {0: class, 1: id, length: 2}
console.log(div.attributes[0]);//class="demo"
console.log(div.attributes[0].value);//demo


DOM树:


Document.prototype.abc='abc';
console.log(document.abc)//abc
HTMLDocument.prototype.abc='abc';
console.log(document.abc)//abc
document-->HTMLDocument.prototype-->Document.prototype
Document.prototype.abc='1';
HTMLDocument.prototype.abc='2';
console.log(document.abc)//2


HTMLBodyElement.prototype.abc='1';
var body = document.getElementsByTagName('body')[0];
var head = document.getElementsByTagName('head')[0];
console.log(body.abc);//1
console.log(head.abc);//undefined


HTMLElement.prototype.abc='1';
var body = document.getElementsByTagName('body')[0];
var head = document.getElementsByTagName('head')[0];
console.log(body.abc);//1
console.log(head.abc);//1
HTML.Document.prototype定义了一些常用的属性head 和body分别指HTML文档中的<head>和<body>标签
document.documentElement属性返回当前文档的根节点(root)。它通常是document节点的第二个子节点,紧跟在document.doctype节点后面。对于HTML网页,该属性返回<html>节点。

document.head属性返回当前文档的<head>节点。

document.body属性返回当前文档的<body>。

document.documentElement===document.querySelector('html')//true
document.head === document.querySelector('head') // true
document.body === document.querySelector('body') // true

getElementById()方法定义在Document.prototype上,即Element节点上不能使用
getElementsByClassName()、getElementsByTagName()、querySelector()、querySelectorAll()在Document.prototype和Element.Prototype上均有定义。

封装函数,返回元素e的第n层祖先元素节点:
function retParent(elem,n){
	while(elem&&n){
		elem = elem.parentElement;
		n--;
	}
	return elem;
}

编辑函数,封装myChiledren功能,解决以前部分浏览器的兼容性问题。

Element.prototype.myChildren = function(){
	var child = this.childNodes;
	var len = child.length;
	var arr = [];
	for(var i = 0; i<len; i++){
		if(child[i].nodeType==1){
			arr.push(child[i]);
		}
	}
	return arr;
}
封装函数,返回元素e的第n个兄弟元素节点,n为正,返回后面的兄弟节点元素,n为负,返回前面的,n为0返回自己。
function retSibling(e,n){
	while(e&&n){
		if(n>0){
			e = e.nextElementSbling;
			n--;
		}else{
			e = elem.previousElementSbling;
			n++
		}
	}
	return e;
}
进行兼容处理:

function retSibling(e,n){
	while(e&&n){
		if(n>0){
			if(e.nextElementSibling){
				e = e.nextElementSibling;
			}else{
				for(e = e.nextSbling;e&&e.nodeType != 1; e = e.nextSbling);
			}
			n--;
		}else{
			if(e.previousElementSibling){
				e = e.previousElementSibling;
			}else{
				for(e = e.previousSbling; e&&e.nodeType != 1;e.previousSibling);
			}
			n++;
		}
	}
	return e;
}

增:

document.createElement();
document.createTextNode();
document.createComment();
document.createDocumentFragment();
插:

append.child():相当于push操作,当元素存在于页面时,进行的是剪切操作

var strong = document.getElementsByTagName('strong')[0];
var text = document.createTextNode('javaScript');
strong.appendChild(text);

<div>
	<span id="span"></span>
	<strong>javaScript</strong>
	<a></a>
</div>
执行下列脚本后:

var strong = document.getElementsByTagName('strong')[0];
var span = document.getElementById('span');
strong.appendChild(span);
html结构变为:

<div>
	<strong>
		javaScript
		<span id="span"></span>
	</strong>
	<a></a>
</div>

<div >
	<strong></strong>
</div>
执行下列脚本后:

var strong = document.getElementsByTagName('strong')[0];
var span = document.createElement('span');
var div = document.getElementsByTagName('div')[0];
div.insertBefore(span,strong);
html结构变为:

<div>
	<span></span>
	<strong></strong>
</div>

删:
parent.removeChild():将元素剪切出来。

child.remove():将元素彻底删除。

替换:

parent.replaceChild(new,origin)

innerHTML():

<div >
	<strong>javaScript</strong>
	<span>CSS</span>
</div>
var div = document.getElementsByTagName('div')[0];
console.log(div.innerHTML);
结果:

"
<strong>javaScript</strong>
<span>CSS</span>
"


innerText:火狐旧版本不兼容,textContent老版本IE不好使。

div.innerText的运行结果:"javaScript CSS"



获取滚动条滚动距离:

function getScrollOffset(){
		if(window.pageXOffset){//IE9以上
			return{
				x : window.pageXOffset,
			    y : window.pageYOffset
			}
			
		}else{
			return{
				x : document.body.scrollLeft + document.HTMLElement.scrollLeft,
				y : document.body.scrollTop + document.HTMLElement.scrollTop
			}
			
		}
	}

获取可视区窗口大小:

function getViewOffset(){
		if(window.innerWidth){
			return {
				w : window.innerWidth,
			    h : window.innerHeight
			}
		}else{//IE8和IE8以下
			if(document.compatMode==="BackCompat"){
				return {
					w : document.body.clientwidth,
					h : document.body.clientHeight
				}
			}else{
				return {
					w : document.documentElement.clientWidth,
					h : document.documentElement.clientHeight
				}
			}
		}
	}

让滚动条滚动:

window上有三个方法:scroll()、scrollTo()和scrollBy()

scrollBy()在之前的数据基础上做累加,可以实现快速阅读的功能。


getComputedStyle(elem,null),第二个参数一般是null,第二个参数表示伪元素,可以是"before"和"after"。



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值