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