首页 > 代码库 > 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获取元素