獲取DOM元素就是利用JS選擇頁面中的標(biāo)簽元素
2.1 根據(jù)CSS選擇器來獲取DOM元素(重點(diǎn))
2.1.1選擇匹配的第一個(gè)元素
語法:
document.querySelector( 'css選擇器' )
參數(shù):
包含一個(gè)或多個(gè)有效的CSS選擇器 字符串
返回值:
CSS選擇器匹配的第一個(gè)元素,一個(gè)HTMLElement對(duì)象。
如果沒有匹配到,則返回null。
2.1.2選擇匹配的多個(gè)元素
語法:
document.querySelectorAll( 'css選擇器' )
參數(shù):
包含一個(gè)或多個(gè)有效的CSS選擇器 字符串
返回值:
CSS選擇器匹配的 NodeList 對(duì)象集合
【示例】
<body>
<div class="box">abc</div>
<div class="box">123</div>
<p id="nav">導(dǎo)航欄</p>
<ul>
<li>1</li>
<li>2</li>
</ul>
<script>
// 1.獲取 div 匹配的第一個(gè)元素
const box = document.querySelector('div')
// const box = document.querySelector('.box')
console.dir(box)
// 2.獲取 p
const nav = document.querySelector('p')
// const nav = document.querySelector('#nav')
console.dir(nav)
// 3.獲取第一個(gè) li
const li = document.querySelector('ul li:first-child')
console.dir(li)
// 4.獲取所有的 li
const lis = document.querySelectorAll('ul li')
console.dir(lis)
</script>
</body>
2.1.3偽數(shù)組
querySelectorAll() 得到的是一個(gè) 偽數(shù)組
?有長(zhǎng)度、有索引號(hào)的數(shù)組
?但是沒有pop() push() 等數(shù)組方法
想要得到里面的每一個(gè)對(duì)象,需要遍歷 (for) 的方式獲得。
哪怕只有一個(gè)元素,通過querySelectAll()獲取過來的也是一個(gè)偽數(shù)組,只是里面只有一個(gè)元素而已
遍歷打印所有的小li :
【示例代碼】文章來源:http://www.zghlxwxcb.cn/news/detail-611219.html
<body>
<ul class="nav">
<li>我的首頁</li>
<li>產(chǎn)品信息</li>
<li>聯(lián)系方式</li>
</ul>
<script>
// 方法1
const lis = document.querySelectorAll('.nav li')
for (let i = 0; i < lis.length; i++) {
console.dir(lis[i])
}
// 方法2
// for (let i = 1; i <= 3; i++) {
// const li = document.querySelector(`ul li:nth-child(${i})`)
// console.dir(li)
// }
</script>
</body>
注意:
(1)獲取一個(gè)DOM元素用querySelector(),能直接操作修改
(2)獲取多個(gè)DOM元素用querySelectorAll(),不能直接操作修改,只能通 過遍歷的方式給里面的元素做修改文章來源地址http://www.zghlxwxcb.cn/news/detail-611219.html
2.2 其他獲取DOM元素方法(了解)
//根據(jù)id獲取一個(gè)元素
document.getElementById( 'nav' )
//根據(jù) 標(biāo)簽 獲取一類元素 獲取頁面所有div
document.getElementsByTagName( 'div' )
//根據(jù) 類名 獲取元素 獲取頁面所有類名為w的
document.getElementsByClassName( 'w' )
到了這里,關(guān)于2.獲取DOM元素的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!