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>

结果:返回一个集合

 

posted @ 2021-12-10 11:32  梦话!  阅读(1313)  评论(0编辑  收藏  举报