js学习笔记DOM获取元素
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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获取元素的主要内容,如果未能解决你的问题,请参考以下文章