0

Suppose I have the following html DOM element:

<input type="checkbox" id="theckboxid" checked="true" />

I know that in Javascript I can access to the checked property (or any other property of the element) by using a bunch of ways. I'll focus on the following two ways:

var isChkd = document.getElementById('theckboxid').checked;

or just

var isChkd = theckboxid.checked;

In both cases the result will be that into the variable isChkd will be stored the Boolean value true. Even using the consolle in Chrome I get exactly the same result.

So the questions are:

Why is better to use getElementById instead the direct use of the id to access the element and its properties?

What are pro and cons of both approaches?

willy wonka
  • 1,440
  • 1
  • 18
  • 31
  • [Because.](https://jsfiddle.net/88ungw5f/) – nnnnnn Mar 18 '17 at 02:07
  • They are not implemented by all browsers and IDs could be invalid variable names like `id="this-is-a-valid-id"`! – ibrahim mahrir Mar 18 '17 at 02:12
  • @nnnnnn Thanks for the immediate response. Sorry not clear: let me better understand: you have kind of redefined as variable the id of the chkbx? Why do I have to do a thing like that? – willy wonka Mar 18 '17 at 02:12
  • I showed you an example of how trying to use the element ID directly as if it is a variable could break, i.e., if an actual variable happens to be defined with the same name. Read the answers in the linked question. – nnnnnn Mar 18 '17 at 02:17
  • @ibrahimmahrir Thanks for the response. Please explicate better "They are not implemented by all browsers". Also I didn't used "this-is-a-valid-id" as var name neither as id... Infact the id I used "theckboxid" is perfectly valid for both uses. – willy wonka Mar 18 '17 at 02:19
  • 1
    The point is using the element ID directly only works *sometimes*. Using `.getElementById()` works all the time. – nnnnnn Mar 18 '17 at 02:27

0 Answers0