1.查詢dom元素document.querySelector與document.querySelectorAll
document.querySelector('.element')
document.querySelector('#element')
document.querySelector('div')
document.querySelector('[name="username"]')
document.querySelector('div + p > span')
將之前的各種getElementByxxxxxx整合到了一起,如果只取第一個元素就使用前者,如果取數組則用後者
這裏要注意後者取出來的是個類數組,想將其轉化爲數組,可以使用拓展運算符(...)或是Array.form()
上述的操作有點冗長,我們可以仿照jquery來簡寫
const $=document.querySelector.bind(document);
$("#element")
2.添加dom元素
.insertAdjacentHTML('beforeend','<p>aaa</p>')//添加html
.insertAdjacentText('beforeend','aaa')//添加文本
.insertAdjacentElement('beforeend',document.createElement('a'))//添加元素
- 'beforebegin': 元素之前
- 'afterbegin': 元素內,第一個子元素之前
- 'beforeend': 元素內,最後一個子元素之後
- 'afterend': 元素之後
3.替換dom元素
oldElement.replaceWith(newElement);//替換
document.querySelector('#oldElement').remove();//移除
4.查詢包含及其他