js獲取dom的三種方式


js獲取dom的方法

1.通過ID獲取  getElementById()

 

<body>
<div id="box"></div>
</body>
<script>
const box=document.getElementById("box")
</script>

 

結果:返回一個dom對象

2.通過類名獲取 getElementsByClassName()

 

<body>
<div class="box"></div>
<div class="box"></div>
</body>
<script>
const boxCollection=document.getElemenstByClassName("box")
const box1=boxList[0]
const box2=boxList[1]
</script>

 

結果:返回一個集合

3.通過name屬性獲取  getElementsByTagName()

<body>
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
</body>
<script>
const p=document.getElemenstByTagName("p")
</script>

結果:返回一個集合

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM