2

I'm new to javascript so while doing some learning i find out that elements with some id available just like

html part

<canvas id="someid"><canvas>

js part

someid.someProperty = something; // works as well as getElementById('someid')

But in all tutorials i found it's told to use getElementById. Sow what benefits of one or another ways of doing this? What way should i prefer? Checked in Firefox, Opera, DWB and geany internal browser(webkit).

3 Answers 3

2

Use document.getElementById("whatever") in all cases. Here are some of the relevant issues:

Using the automatic global variable has these issues:

  • Not a standard defined behavior
  • Not supported in all browsers
  • Vulnerable to global namespace clashes
  • Some name attributes (but not all) can be used this way
  • Can have collisions between id and name
  • Code is less readable because the reader has to figure out whether you're using a global variable that you've previously put a value in or whether this is an automatically defined variable.

Using document.getElementById():

  • Is supported by the standard
  • Is supported in all browsers
  • Does not rely on any global variables
  • Unambiguous behavior in all uses
Sign up to request clarification or add additional context in comments.

Comments

1

Some browsers create implicit global variables for named DOM elements. Referencing an element this way in Firefox produces the following warning:

"Element referenced by ID/NAME in the global scope. Use W3C standard document.getElementById() instead."

Follow that warning's advice. Using getElementById:

  • is supported by the standard
  • is explicit (and therefore more clear)
  • requires you to create an appropriately-scoped variable for each element you want to reference
  • is more recognizable to modern developers

There are no good reasons to use the non-standard method.

Comments

0

For JS you plan to write it's always good to manually bound variables to DOM elements, otherwise you could get undesired results if some Object is bound to the window object and shared the same ID name as your element

var someid = {}; // Some Object

someid.style.color = "red";  // DOM element remains untouched
// we just nested properties and values to the 'someid' Object.
// #someid text has not become red.

var myElement = document.getElementById('someid');
// var myElement = querySelector('#someid');
myElement.style.color = "red";
// Wow, now it is

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.