首页 > 代码库 > js学习笔记(三)DOM获取元素
js学习笔记(三)DOM获取元素
1. getElementById操作示例
<!DOCTYPE HTML><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Shopping list</title></head><body><h1>What to buy</h1><p title="a gentle reminder">Don‘t forget to buy this stuff.</p><ul id="purchases"> <li>A tin of beans</li> <li class="sale">Cheese</li> <li class="sale important">Milk</li></ul><script>alert(typeof document.getElementById("purchases"));</script></body></html>
2. getElementsByTagName操作示例
<!DOCTYPE HTML><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Shopping list</title></head><body><h1>What to buy</h1><p title="a gentle reminder">Don‘t forget to buy this stuff.</p><ul id="purchases"> <li>A tin of beans</li> <li class="sale">Cheese</li> <li class="sale important">Milk</li></ul><script>var items = document.getElementsByTagName("li"); /*getElementsByTagName获取没有id属性的对象并赋值给items变量*/for(var i=0; i<items.length; i++){ alert(typeof items[i]);}</script></body></html>
<!DOCTYPE HTML><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Shopping list</title></head><body><h1>What to buy</h1><p title="a gentle reminder">Don‘t forget to buy this stuff.</p><ul id="purchases"> <li>A tin of beans</li> <li class="sale">Cheese</li> <li class="sale important">Milk</li></ul><script>var shopping = document.getElementById("purchases"); /*获取当前id元素purchases*/var items = shopping.getElementsByTagName("*"); /*获取当前id元素purchases的所有子元素*/for(var i=0; i<items.length; i++){ alert(typeof items[i]);}</script></body></html>
3. getElementsByClassName操作示例
<!DOCTYPE HTML><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Shopping list</title></head><body><h1>What to buy</h1><p title="a gentle reminder">Don‘t forget to buy this stuff.</p><ul id="purchases"> <li>A tin of beans</li> <li class="sale">Cheese</li> <li class="sale important">Milk</li></ul><script>var shopping = document.getElementById("purchases"); /*获取当前id元素purchases*/var sales = shopping.getElementsByClassName("sale"); /*获取当前id元素purchases的所有包含类名sale的元素*/alert(sales.length);</script></body></html>
js学习笔记(三)DOM获取元素
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。