元素选择
单个元素选择
// 任何可用的css选择器
document.querySelector('selector')
// demo
document.querySelector('.foo') // 类选择器
document.querySelector('#id') // id选择器
docuemtn.querySelector('div') // 标签选择器
document.querySelector('[name="foo"]' // 标签选择器
复制代码
如果没有找到符合的元素则返回null。
多个元素选择
document.querySelectorAll('p') // 选择所有的p标签
复制代码
使用querySelectorAll
如果有找到符合的元素,会返回一个静态NodeList
,如果没有找到则返回一个空NodeList
。
NodeList
是一个可迭代的类数组对象,可以用forEach
循环遍历;但是不支持filter
, map
, reduce
等方法,如果要实现filter
等方法可以通过Array.from
或[…NodeList]转成数组再进行操作。
querySelectorAll
返回的是静态的NodeList
, 而getElementsByTagName
, getElementByClassName
返回的是一个动态的HTMLCollection
,所以动态的增减DOM
元素对querySelectorAll
是无感的;两者之前的另外一个区别是NodeList
能包含任意类型的Node
,而HTMLCollection
只能包含HTMLElement
。
向上查找DOM元素
通过closest方法找到符合的最近父元素。
document.querySelector('p')
.closest('div')
.closest('.content') // 支持链式操作
复制代码
添加元素
insertAdjacentHTML方法支持添加任何HTML字符串到DOM中。
document.body.insertAdjacentHTML('beforeend',
'<a href="https://juejin.cn/home" class="active">Home</a>');
复制代码
该方法的第一个参数支持控制插入位置
- beforebegin 插入到元素的前面
- afterbegin 插入到第一个子元素的前面
- beforeend 插入到最后一个子元素的后面
- afterend 插入到元素后面
<!-- beforebegin -->
<p>
<!-- afterbegin -->
foo
<!-- beforeend -->
</p>
<!-- afterend -->
复制代码
还有一个与insertAdjacentHTML等价的方法,向DOM添加元素。
const link = document.createElement('a')
const p = document.querySelector('p')
p.insertAdjacentElement('beforebegin', link)
复制代码
另外如果是添加TEXT的话,可以通过insertAdjacentText方法来添加文本。
const p = document.querySelector('p')
p.insertAdjacentText('beforeend', 'foo')
复制代码
移动元素
通过insertAdjacentElement方法也能实现元素的移动。
如果有如下的DOM结构
<div class="first">
<h1>Title</h1>
</div>
<div class="second">
<h2>Subtitle</h2>
</div>
复制代码
把h2移动到h1的后面
const h1 = document.querySelector('h1')
const h2 = document.querySelector('h2')
h1.insertAdjacentElement('afterend', h2)
复制代码
通过上面的代码会实现如下效果
<div class="first">
<h1>Title</h1>
<h2>Subtitle</h2>
</div>
<div class="second">
</div>
复制代码
替换元素
可以通过replaceWith方法实现DOM元素的替换。
someELement.replaceWith(otherELement)
复制代码
该方法会用新创建的元素或者已经存在的元素来替换元素。
<div class="first">
<h1>Title</h1>
</div>
<div class="second">
<h2>Subtitle</h2>
</div>
const h1 = document.querySelector('h1');
const h2 = document.querySelector('h2');
h1.replaceWith(h2);
// result:
<div class="first">
<h2>Subtitle</h2>
</div>
<div class="second">
</div>
复制代码
移除元素
通过remove方法来移除元素。
const container = document.querySelector('container')
container.remove()
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END