#神仙见了会流泪之#getElementsByTagName的用法

时间:2024-11-18 14:29:17
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> *{ margin: 0; padding: 0; list-style: none; } body{ width: 800px; margin-left: auto; margin-right: auto; } #city-list{ float: left; width: 450px; } #inner{ width: 400px; border-style: solid; border-width: 1px; margin-bottom: 10px; padding: 10px; float: left; } #inner li{ border-style: solid; border-width: 1px; padding: 5px; margin: 5px; background-color: #99ff99; float: left; } #btn-l{ float: left; } #btn{ width: 50px; } </style> <script> window.onload = function(){ /*需求:点击按钮查找id为city下所有li节点*/ //获取btn并给btn设置单机响应函数 var btn = document.getElementById("btn") btn.onclick = function(){ //获取id为city的元素 var city = document.getElementById("city") //查找city下的li节点 var lis = city.getElementsByTagName("li") for(var i = 0;i < lis.length; i++){ alert((lis[i]).innerHTML) } } } </script> </head> <body> <div id="city-list" > <div id="inner" > <ul id="city" > <li>北京</li> <li>上海</li> <li>广州</li> <li>澳门</li> </ul> </div> </div> <div id="btn-l" > <div ><button id="btn" >按钮</button></div> </div> </body> </html>