document.getElementById/Name/TagName返回值的小区别

document.getElementById/Name/TagName这三个可以取得元素,分别通过查询id、name和标签名。但他们的返回值室友区别的。
下面来看个简单的例子:

<div id="myDiv" name="sb" class="bd" title="Body text" lang="en" dir="ltr" my_special_attribute="hello!">Some text</div>  
<script>  
    //document.write(document.getElementById("myDiv")+"<br>");  
    //document.write(document.getElementsByName("sb")+"<br>");  
    //document.write(document.getElementsByTagName("div")+"<br>");  
    document.write(document.getElementById("myDiv").getAttribute("my_special_attribute"));  
    document.write(document.getElementsByName("sb").getAttribute("my_special_attribute"));  
    document.write(document.getElementsByTagName("div").getAttribute("my_special_attribute"));  
</script>  

如代码所示:
document.getelementsByName和document.getelementsByTagName在这里的用法是错误的。原因是getelementById返回的是对象(具有相同id属性的第一个),getelementsByName和getelementsByTagName返回的是数组对象。
如果要使用getelementsByName和getelementsByTagName返回具体的对象,就要进行索引,代码如下:

document.write(document.getElementsByName("sb")[0].getAttribute("my_special_attribute"));  
document.write(document.getElementsByTagName("div")[0].getAttribute("my_special_attribute"));  

多写一点这段代码里容易犯的小错误(与本文主题无关),就是换行的实现。我们都知道在HTML中换行用</br>(或<br>),在javascript中换行用转义符\n。
但在本段代码中document.write()用的<br>,和上述规则不同,这是因为document.write()的内容是输出到HTML中,所以采用<br>。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、JS前言 (1)认识JS 也许你已经了解HTML标记(也称为结构),知道了CSS样式(也称为表示),会使用HT...
    凛0_0阅读 7,748评论 0 8
  • 第1章 认识JS JavaScript能做什么?1.增强页面动态效果(如:下拉菜单、图片轮播、信息滚动等)2.实现...
    mo默22阅读 5,211评论 0 5
  •   DOM(文档对象模型)是针对 HTML 和 XML 文档的一个 API(应用程序编程接口)。   DOM 描绘...
    霜天晓阅读 9,080评论 0 7
  • 一、概述 document节点是整个文档树的顶层节点,每张网页都有自己的document节点。window.doc...
    周花花啊阅读 5,157评论 0 1
  • 概述 document节点是文档的根节点,每张网页都有自己的document节点。window.document属...
    许先生__阅读 3,914评论 0 2