JavaScript和getElementById用于具有相同ID的多个元素 [英] JavaScript and getElementById for multiple elements with the same ID

查看:916
本文介绍了JavaScript和getElementById用于具有相同ID的多个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过指定 id 属性来获取元素集合?我想获取html中具有相同 id 的所有标签的名称。

How can I get a collection of elements by specifying their id attribute? I want to get the name of all the tags which have the same id in the html.

我想要仅使用 getElementById()来获取元素数组。我怎么能这样做?

I want to use ONLY getElementById() to get an array of elements. How can I do this?

推荐答案

HTML规范要求 ID 属性在页面中是唯一的:

The HTML spec required the ID attribute to be unique in a page:


此属性为元素指定名称。此名称在文档中必须是唯一的。

This attribute assigns a name to an element. This name must be unique in a document.

如果您有多个具有相同ID的元素,则您的HTML无效。

If you have several elements with the same ID, your HTML is not valid.

因此, getElementById()应该只返回一个元素。你不能让它返回多个元素。

So, getElementById() should only ever return one element. You can't make it return multiple elements.

有几个相关的函数会返回一个元素数组 - getElementsByName getElementsByClassName 可能更适合您的要求,但 getElementsByClassName 是HTML 5的新手,仍处于草稿状态。

There are a couple of related functions that will return an array of elements - getElementsByName, or getElementsByClassName that may be more suited to your requirements, though getElementsByClassName is new to HTML 5, which is still in draft.

这篇关于JavaScript和getElementById用于具有相同ID的多个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆