3

I am new to programming and have a question regarding HTML elements with id attributes. My question is - if an HTML element has an id attribute, is the value of the id attribute readily usable without defining it in JavaScript? Here is an example to make this more clear:

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="UTF-8" />
      </head>
      <body>
        <input type="checkbox" id="mycheckbox" checked />
        <input type="radio" id="myradio" checked />
        <p id="test">
          p tag too.
        </p>

        <script>
          if(mycheckbox.checked) {
            alert("How does this work?  Are there more pre-defined stuff (varaibles?) like this one?");
          }
          if(myradio.checked) {
            alert("Another example with radio");
          }
          alert(test.innerHTML);
        </script>

      </body>

I have read some books on JavaScript and none have given this shortcut method (if it is one) of working with HTML elements.

Thank you in advance.

Aakash
  • 21,375
  • 7
  • 100
  • 81
  • 1
    it may works because of backward compatibility for old dark times when ie6 was browser, but its not recommended. use `document.getElementById()` instead – Peter Jun 06 '15 at 13:11
  • 2
    http://stackoverflow.com/questions/3434278/do-dom-tree-elements-with-ids-become-global-variables – AmmarCSE Jun 06 '15 at 13:16
  • I suggest you to read about [DOM](https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model/Introduction) to understand the link between HTML and javascript – Ander2 Jun 06 '15 at 13:28

1 Answers1

0

Its recommended to use document.getElementById(id) instead. http://www.w3.org/TR/html51/browsers.html#named-access-on-the-window-object

Or $('#id') if you are using the jQuery library, which I would personally recommend to make things easier for you. To use its methods you just have to include the link to the jQuery script (eg from a CDN) in a tag

Source: http://api.jquery.com/id-selector/

CyborgFish
  • 356
  • 6
  • 13
  • This answer is wrong. –  Jun 06 '15 at 13:30
  • @torazaburo maybe it could still be useful if you pointed out the mistake. Thank you anyway. – CyborgFish Jun 06 '15 at 13:38
  • 2
    @CyborgFish It's wrong because says "no", but the spec says "yes". See [Named access on the Window object](http://www.w3.org/TR/html51/browsers.html#named-access-on-the-window-object). But `getElementById` is much better practice. – Oriol Jun 06 '15 at 15:37
  • @Oriol Edited with your info, now it doesnt say "no", but I kept the best practice recommendation. Thanks. – CyborgFish Jun 06 '15 at 16:06