如何获取节点元素呢?
代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="GB2312"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <script type="text/javascript"> window.onload = function(){ var bjName = document.getElementById("bj"); alert(bjName); var bjId = document.getElementsByName("beijing"); alert(bjId.length); var list = document.getElementsByTagName("li"); alert(list.length); } </script> </head> <body> <p>你喜欢哪个城市</p> <ul id="City"> <li id="bj" name="beijing">北京</li> <li id="Sh">上海</li> <li>广州</li> <li>深圳</li> </ul> <br/> <p>你喜欢哪款单机游戏</p> <ul id="game"> <li>反恐精英</li> <li>魔兽</li> <li>红警</li> <li>实况</li> </ul> </body> </html>
说明:
<script type="text/javascript"> window.onload = function(){ var bjName = document.getElementById("bj"); alert(bjName); var bjId = document.getElementsByName("beijing"); alert(bjId.length); var list = document.getElementsByTagName("li"); alert(list.length); } </script>
document.getElementById("ID"):是整个文档的方法,使用该方法时确保ID唯一。
document.getElementByName("属性名"):是对于元素自身没有的定义的属性使用该方法,例如li没有Name这个属性所以使用BYName().但是IE不支持该方法,使用需谨慎。
<script type="text/javascript"> window.onload = function(){ var CityNode = document.getElementById("City"); var list = CityNode.getElementByTagName("li"); alert(list.length); } </script>
document.getElementByTagName("TagName"):获取标签为TagName的所有元素,会在整个文档中找所有tagName的所有元素。