What practical problem will i face if i use same #id more than one time on a page , other than validation error “ID is already defined”?

前端 未结 7 755
甜味超标
甜味超标 2021-01-13 15:09

First of all I alwyas use one #ID. just asking this question to know deep reason behind it.

Is it only a matter of W3C validation? or more than that

相关标签:
7条回答
  • 2021-01-13 15:39

    The result is undefined.

    Apart from what the rest said about getElementById:

    • using #foo in CSS may apply to all elements with id="foo", or to the first, or to the last, depending on how the browser is implemented.
    • using page.html#foo in a URL may scroll to one of the elements, or to the other, or to neither.

    edit: either way, you should teach your students to do things right even if doing it wrong doesn't seem to have any immediate bad consequences... ;)

    0 讨论(0)
  • 2021-01-13 15:40

    I've had experiences where certain JavaScript code didn't work as expected because two elements had the same ID. I think getElementById just gets the first element it comes to that has the particular ID.

    0 讨论(0)
  • 2021-01-13 15:43

    "Why I'm saying css #ID should be used once in a page (to my students)?"

    "Imagine the trouble it would cause if lots of countries had the same name. ID is identity. Many countries can be an island, or tropical, or as small as a carpet but think of the trouble it would cause if 50 countries were called San Marino."

    0 讨论(0)
  • 2021-01-13 15:46

    At a minimum, Javascript code which uses getElementById() will return only one of the matching elements - which one will be undefined, and hence subject to cross-browser differences.

    0 讨论(0)
  • 2021-01-13 15:51

    document.getElementById() won't work reliably.

    0 讨论(0)
  • 2021-01-13 15:59

    This post is just to add some more points to this interesting discussion ..

    Its true that .. Id must have been unique and usage of 'duplicate IDs' must have been depreciated by browsers itself ..
    But may be because these browsers want to make it more coder-friendly, don't seriously consider the "id" matter ..
    So apart from javascript this mistake doesn't matter much to us too ...
    (Depends on the version of the different browsers) Even CSS has no problem with it .. (apart from validation errors) check this out ..

    <head>
    <style type="text/css">
      #Button{color:red;}
    </style>
    </head>
    <body>
    <form>
    <input id="Button" type="button" value="Click me"/>
    <input id="Button" type="text" value="Type Here"/>
    </form>
    </body>
    

    But I assure that in-case of javascript usage it is prone to hell of bugs .. Once I had faced this problem .. where I had used same name for ID as well as NAME .. !

    :-)

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