文档对象模型 获取对象 1.根据id属性值获取,返回单个对象 var h1 = document.getElementById('h1'); 2.根据标签名获取,返回对象数组 var divs = document.getElementByTagName('div'); 3.根据name属性值获取,返回对象数组 var hobbys = document.getElementByName('hobby'); 4.根据class属性值获取,返回对象数组 var clss = document.getElementByClassName('cls'); //例: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <img id = "h1" src="C:\Users\Lenovo\Desktop\ps图片\25D383AB7DDEA10CAF3EB83147A1843B.gif"><br><br> <div class="cls">**李坤雪**</div> <br> <div class="cls"> 大傻猪 </div> <br> <input type="checkbox" name="hobby"> 爱玩 <input type="checkbox" name="hobby"> 心大 <input type="checkbox" name="hobby"> 爱哭 </body> <script> //根据id获取元素 //var img = document.getElementById('h1'); //alert(img); //根据标签获取元素 //var divs = document.getElementsByTagName('div'); //for (let i = 0; i< divs.length; i++) { // alert(divs[i]); //} //根据name属性获取元素 var ins = document.getElementsByName('hobby'); for (let i = 0; i< ins.length; i++) { alert(ins[i]); } //根据class属性获取元素 var divs = document.getElementsByClassName('cls'); for (let i = 0; i< divs.length; i++) { alert(divs[i]); } </script> </html> //2.利用获取到的元素进行操作
标签:13,JavaScript,2023.10,alert,获取,var,document,divs,属性 From: https://www.cnblogs.com/muzhaodi/p/17762911.html