Is it okay to not use "document.getElementById('myId')" in JavaScript when accessing elements with IDs?
The reason why you can access elements by their ID without using "document.getElementById('myId')" is because browsers store references to elements with IDs in the global namespace, making them accessible as variables. However, relying on this behavior is not recommended due to the crowded nature of the global namespace which can lead to conflicts.
For example, if you have a div with an ID of "foo" and a function named foo, simply referencing "foo" in your code will give you the function, not the element.
It's important to note that automatic element globals are covered in the HTML5 spec, but it's best practice to intentionally retrieve elements using methods like getElementById or querySelector to avoid potential conflicts in the future.
Does not storing the ID in a variable result in more DOM traversal?
Since the ID is already a global variable, there is no additional DOM traversal required. In some cases, there may be more scope chain traversal in deeply-nested functions, but this is typically negligible.
Although accessing elements with IDs directly is fast, it's recommended to explicitly fetch elements using appropriate methods for better code organization and to prevent conflicts. Caching references may not be necessary for performance reasons, but can offer added convenience in coding practices. Selectors like querySelector and querySelectorAll may be slightly slower than getElementById, but optimizations should only be considered if performance issues arise.