FrankKai / FrankKai.github.io

FE blog
https://frankkai.github.io/
362 stars 39 forks source link

DOM进阶之Element和NodeList #190

Open FrankKai opened 4 years ago

FrankKai commented 4 years ago

Element

在Document继承中,Element几乎是所有元素对象的基类。它拥有很多通用的方法和属性。有很多特殊的class继承自Element,比如说HTMLElement,SVGElement。 一句话概括的话就是:Element几乎是前端的鼻祖class,有必要一探究竟。

image

Element又继承自Node和EventTarget,可以查阅:DOM进阶之EventTargetDOM进阶之Node

属性

Element有非常多的属性。 attributes,classList,className,clientHeight,clientLeft,clientTop,clientWidth,Element.id,Element.innerHTML,localName,namespaceURI,outerHTML,prefix,scrollHeight,scrollTop,scrollWidth,tabName

方法

Element有非常多的方法 addEventListener,attachShadow,dispatchEvent,getAttribute,getAttributeNames,getBoundingClientRect,getElementsByClassName,getElementByTagName,hasAttributes,insertAdjacentElement,querySelector,querySelectorAll,removeAttribute,removeEventListener,scroll,scrollBy,scrollIntoView,scrollTo,setAttribute,toggleAttribute

事件

可以使用addEventListener添加事件。 cancel,error,scroll,select,show,whell copy,cut,paste compositioned,compositionstart,compositionupdate blur,focus,focusin,focusout fullscreenchange,fullscreenerror keydown,keypress,keyup auxclick,click,contextmenu,dbclick,mousedown,mouseenter,mouseleave,mousemove,mouseout,mouseover,moseup touchcancel,touchend,touchmove,touchstart

NodeList

两种类型的NodeList:live和static

Live NodeLists

live类型的NodeLists意味着当发生变化时,DOM会自动更新这个集合

一个live NodeList例子:

const parent = document.getElementById('parent');
const child_nodes = parent.childNodes;
console.log(child_nodes.length); // 2
parent.appendChild(document.createElement('div'));
console.log(child_nodes.length); // 3
static NodeLists

static类型的NodeList意味着发生变化时,DOM不会影响这个集合。

通过无处不在的document.querySelectorAll()方法可以返回static NodeLists。

在选择如何遍历NodeList中的项以及是否应该缓存列表的长度时,最好记住这一区别。

方法

item(),entries(),forEach(),keys(),values()

如何遍历NodeList

Element与NodeList的区别

通过document.querySelector()返回的是一个Element。通过document.querySelectorAll()返回的是一个NodeList。

如果对document.querySelector()和document.querySelectorAll()存疑的话,可以查阅:DOM进阶之querySelector和querySelectorAll

参考资料

https://developer.mozilla.org/en-US/docs/Web/API/Element https://developer.mozilla.org/en-US/docs/Web/API/NodeList