querySelector系列方法相比 getElementsBy 系列方法有什么区别?

  • querySelector 和  querySelectorAll 相比下面这些方法有什么区别?

getElementsByTagName

getElementsByClassName

getElementsByName

  • 1. W3C 标准

querySelectorAll 属于 W3C 中的 Selectors API 规范 。而 getElementsBy 系列则属于 W3C 的 DOM 规范

  • 2. 浏览器兼容

querySelectorAll 已被 IE 8+、FF 3.5+、Safari 3.1+、Chrome 和 Opera 10+ 良好支持 。

getElementsBy 系列,以最迟添加到规范中的 getElementsByClassName 为例,IE 9+、FF 3 +、Safari 3.1+、Chrome 和 Opera 9+ 都已经支持该方法了。

  • 3. 接收参数

querySelectorAll 方法接收的参数是一个 CSS 选择符。而 getElementsBy 系列接收的参数只能是单一的className、tagName 和 name。代码如下

var c1 = document.querySelectorAll('.b1 .c');
var c2 = document.getElementsByClassName('c');
var c3 = document.getElementsByClassName('b2')0].getElementsByClassName('c');

需要注意的是,querySelectorAll 所接收的参数是必须严格符合 CSS 选择符规范的。

  • 4. 返回值

=querySelectorAll 返回的是一个 Static Node List,而 getElementsBy 系列的返回的是一个 Live Node List。

		var qq1 = document.getElementsByClassName("qq");
		var qq2 = document.querySelectorAll(".qq");
		console.log(qq1);
		console.log(qq2);

看浏览器的返回结果

HTMLCollection [ <div.qq>, <div.qq>, <div.qq>, <div.qq> ]
NodeList [ <div.qq>, <div.qq>, <div.qq>, <div.qq> ]

NodeList 对象会包含文档中的所有节点,如 Element、Text 和 Comment 等。

HTMLCollection 对象只会包含文档中的 Element 节点。

所以在现代浏览器中,querySelectorAll 的返回值是一个静态的 NodeList 对象,而 getElementsBy 系列的返回值实际上是一个 HTMLCollection 对象 。

  • 5.在举个例子
		var qq1 = document.getElementsByClassName("qq");
		var qq2 = document.querySelectorAll(".qq");
                console.log(qq1);
                console.log(qq2);   
		for(var i = 0; i < qq1.length; i++) {
			qq1[i].onclick = function() {
				this.parentNode.removeChild(this);
				console.log(qq1);
			}
		}

把qq1内容点击删除之后,结果如左边的图,再把上面代码for循环里面的qq1改成qq2,连续点击删除之后结果如右边的图

Nodelist虽然html中的元素在浏览器界面删除了,但是在数组中还是存在这几个元素;

HTMLCollection,元素删除,数组也删除。

所以在现代浏览器中,querySelectorAll 的返回值是一个静态的 NodeList 对象,而 getElementsBy 系列的返回值实际上是一个 HTMLCollection 对象 。

在一般情况中他们两个是差不多的,但是如果你需要多次复杂操作取到的数组的话他们两个会有所区别。

我也是在前几天遇到的情况,后来查资料才知道他们有这种区别。希望对大家所帮助,不对的地方希望大神指点!!

 

 

 

 

原文地址:https://www.cnblogs.com/dengting/p/5833235.html