DEV Community

Discussion on: Dark Mode in 3 Lines of CSS and Other Adventures

Collapse
 
l10nelw profile image
Lionel Wong • Edited
<fieldset id="colorScheme">
Enter fullscreen mode Exit fullscreen mode
colorScheme.addEventListener(...)
Enter fullscreen mode Exit fullscreen mode

What is the general consensus in the community about referencing elements like this? As opposed to:

document.getElementById('colorScheme').addEventListener(...)
Enter fullscreen mode Exit fullscreen mode

Isn't it considered unsafe and error-prone? I don't really remember, it's rarely seen in the wild, perhaps for a reason.

Collapse
 
wadecodez profile image
Wade Zimmerman

It's best practice to use document.getElementById over the global variable because defining a local variable colorScheme would take precedence. It's also annoying to debug these global variables because they are not explicitly defined. When searching for something like colorScheme = you won't find anything, and finding something like colorScheme.addEventListener tells you nothing about the type of variable. However, finding document.getElementById tells you it's a DOM element.

Collapse
 
adam_cyclones profile image
Adam Crockett 🌀

I vote that implicit code is dangerous code and explicit code is safe code and there is no grey area 🫣

Collapse
 
madsstoumann profile image
Mads Stoumann

(see updated feedback above)

Collapse
 
madsstoumann profile image
Mads Stoumann

When I write example-code for articles, I tend to omit selectors, because I want to focus on what the code does, rather than how to select a Node in the DOM.
I assume most of Dev.to's readers knows how to do that anyway, and might want to use their own selectors (class-based, attribute-based, something else?) instead of just copy/pasting the code.

But I could be wrong! So thank you for your feedback — I've added this to the article:

const colorScheme = document.getElementById('colorScheme');
Enter fullscreen mode Exit fullscreen mode