Element
上一篇文章整理了Elemtnt浏览器的Element - 属性 - 掘金 (juejin.cn),这篇接着整理Element的方法。
attribute 相关
getAttribute(attrName)- 获取一个attrName的valuegetAttributeNames()- 获取当前元素的全部attr名称hasAttribute(attrName)- 判断是否存在attrName这个属性hasAttributes(attrName1,attrName2,attrName3,...)- 判断是否存在多个属性的其中一个removeAttribute(attrName)- 溢出属性attrNamesetAttribute(attrName)- 设置属性attrName的valuetoggleAttribute(attrName)- 反转bool属性attrName
元素添加删除相关
element.insertAdjacentElement(position, element1);
element.insertAdjacentHTML(position, domStr);
element.insertAdjacentText(position, str);
将一个给定的元素节点插入到相对于被调用的元素
element的给定的一个position位置。element1: 是一个元素Element
domStr: 是DomString,字符串的html
str: 字符串,text文本
position: 表示相对于该元素的位置;必须是以下字符串之一:
'beforebegin': 在该元素本身的前面。'afterbegin':只在该元素当中,在该元素第一个子孩子前面。'beforeend':只在该元素当中,在该元素最后一个子孩子后面。'afterend': 在该元素本身的后面。
remove()(en-US) - 移除当前元素
元素查找相关
getElementsByClassName(class)- 根据class名称查找所有元素getElementsByTagName()- 根据tag 查找所有元素注意:
Elementclass 没有getElementById方法,getElementById是属于Document的方法querySelector(stringSelector)- 按照stringSelector查找出第一个符合要求的元素querySelectorAll(stringSelector)- 按照stringSelector查找出所有符合要求的元素matches(stringSelector)- 判断是否存在符合stringSelector要求的元素closest(stringSelector)- 找到上层tree关系中,符合stringSelector的元素,包括元素自己
元素位置相关
getBoundingClientRect()getClientRects()获取当前元素的位置和边长信息:x,y,top,left,bottom,right
注意,这些数据包括padding
scroll(x,y)scrollBy(x,y)scrollTo(x,y)scroll和scrollTo没有区别,但是把当前元素内部的滚动条滚动到对应的x,y。
scrollBy是把当前元素内部的滚动条在当前基础上再移动一个x,y距离。
注意: 这三个方法只有在当前元素内部可以滚动的情况下有意义呀。scrollIntoView()让当前元素在父元素的滚动下加入屏幕的可见范围
scrollIntoView() scrollIntoView(alignToTop) scrollIntoView(scrollIntoViewOptions) // alignToTop: boolean. // 如果为 `true`,元素的顶端将和其所在滚动区的可视区域的顶端对齐。相应的 `scrollIntoViewOptions: {block: "start", inline: "nearest"}`。这是这个参数的默认值。 // 如果为 `false`,元素的底端将和其所在滚动区的可视区域的底端对齐。相应的 `scrollIntoViewOptions: {block: "end", inline: "nearest"}`。
其他
attachShadow()animate()- 给元素添加动画效果getAnimations()(en-US) 实验性computedStyleMap()实验性requestFullscreen()- 让当前元素退出全屏模式requestPointerLock()- 取消当前元素的鼠标锁定