Can multiple different HTML elements have the same ID if they're different elements?

后端 未结 16 1723
无人及你
无人及你 2020-11-21 05:30

Can multiple HTML elements have the same ID if they\'re of different element types? Is a scenario like this valid? Eg:

div#foo
span#foo
a#foo
相关标签:
16条回答
  • 2020-11-21 05:47

    No.

    Element IDs should be unique within the entire document.

    0 讨论(0)
  • 2020-11-21 05:47

    Is it possible to have more than one student in a class having same Roll/Id no? In HTMLid attribute is like so. You may use same class for them. e.g:

    <div class="a b c"></div>
    <div class="a b c d"></div>
    

    And so on.

    0 讨论(0)
  • 2020-11-21 05:48

    We can use class name instead of using id. html id are should be unique but classes are not. when retrieving data using class name can reduce number of code lines in your js files.

    $(document).ready(function ()
    {
        $(".class_name").click(function ()
        {
            //code
        });
    });

    0 讨论(0)
  • 2020-11-21 05:50

    I think you can't do it because Id is unique you have to use it for one element . You can use class for the purpose

    0 讨论(0)
  • 2020-11-21 05:54

    Yes they can.

    I don't know if all these anwers are outdated, but just open youtube and inspect the html. Try to inspect the suggested videos, you'll see that they all have the same Id and repeating structure as follows:

    <span id="video-title" class="style-scope ytd-compact-radio-renderer" title="Mix - LARA TACTICAL">
    
    0 讨论(0)
  • 2020-11-21 05:55

    <div id="one">first text for one</div>
    <div id="one">second text for one</div>
    
    var ids = document.getElementById('one');

    ids contain only first div element. So even if there are multiple elements with the same id, the document object will return only first match.

    0 讨论(0)
提交回复
热议问题