JS获取网页中HTML元素的几种方法分析
来源:天极网 时间:2007-10-12 13:08:00
JS获取网页中HTML元素的几种方法分析:getElementById getElementsByName getElementsByTagName 大概介绍
getElementById ,getElementsByName ,getElementsByTagName
后两个是得到集合,byid只是得到单个对象
getElementById 的用法
举个例子:
<a id="link1" name="link1" href=http://www.aspxhome.com>asp之家</a>
同一页面内的引用方法:
1、使用id:
link1.href,返回值为http://www.aspxhome.com
2、使用name:
document.all.link1.href,返回值为http://www.aspxhome.com
3、使用sourseIndex:
document.all(4).href //注意,前面还有HTML、HEAD、TITLE和BODY,所以是4
4、使用链接集合:
document.anchors(0).href
//全部的集合有all、anchors、applets、areas、attributes、behaviorUrns、bookmarks、boundElements、cells、childNodes、children、controlRange、elements、embeds、filters、forms、frames、images、imports、links、mimeTypes、options、plugins、rows、rules、scripts、styleSheets、tBodies、TextRectangle,请参考MSDN介绍。
其实方法3和方法4是一样使用的集合,只是一个是all,可以包括页面所有标记,而anchors只包括链接。
5、getElementById:
document.getElementById("link1").href|||
6、getElementsByName:
document.getElementsByName("link1")[0].href //这也是一个集合,是所有name等于该方法所带参数的标记的集合
7、getElementsByTagName:
document.getElementsByTagName("A")[0].href //这也是一个集合,是所有标记名称等于该方法所带参数的标记的集合