Are html elements with IDs already defined in JavaScript?

I am new to programming and have a question about HTML elements with id attributes. My question is, if an HTML element has an id attribute, is the value of the id attribute easily accessible without defining it in JavaScript? Here's an example to make it clearer:

    <!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've read several JavaScript books and none of them have given this shortcut method (if there is one) of working with HTML elements.

Thanks in advance.

+3


source to share


1 answer


It is recommended to use instead document.getElementById(id)

. 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 personally would recommend making it easier for you. To use its methods, you just need to include a link to the jQuery script (for example from a CDN) in the tag



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

0


source







All Articles