JavaScript and getElementById for multiple element

2019-01-02 20:55发布

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.

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

标签: javascript
12条回答
梦该遗忘
2楼-- · 2019-01-02 21:18

Why you would want to do this is beyond me, since id is supposed to be unique in a document. However, browsers tend to be quite lax on this, so if you really must use getElementById for this purpose, you can do it like this:

function whywouldyoudothis() {
    var n = document.getElementById("non-unique-id");
    var a = [];
    var i;
    while(n) {
        a.push(n);
        n.id = "a-different-id";
        n = document.getElementById("non-unique-id");
    }

    for(i = 0;i < a.length; ++i) {
        a[i].id = "non-unique-id";      
    }
    return a;
}

However, this is silly, and I wouldn't trust this to work on all browsers forever. Although the HTML DOM spec defines id as readwrite, a validating browser will complain if faced with more than one element with the same id.

EDIT: Given a valid document, the same effect could be achieved thus:

function getElementsById(id) {
  return [document.getElementById(id)];
}
查看更多
与风俱净
3楼-- · 2019-01-02 21:20

It is illegal to have multiple elements with the same id. The id is used as an individual identifier. For groups of elements, use class, and getElementsByClassName instead.

查看更多
梦寄多情
4楼-- · 2019-01-02 21:20

document.querySelectorAll("#yourId"); returns all elements whose id is yourId

查看更多
一个人的天荒地老
5楼-- · 2019-01-02 21:22

The id is supposed to be unique, use the attribute "name" and "getelementsbyname" instead, and you'll have your array.

查看更多
余生无你
6楼-- · 2019-01-02 21:24

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.

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

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

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.

查看更多
余生无你
7楼-- · 2019-01-02 21:24

we can use document.forms[0].Controlid

查看更多
登录 后发表回答