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.
How’s it going, I'm a Adam, a Full-Stack Engineer, actively searching for work. I'm all about JavaScript. And Frontend but don't let that fool you - I've also got some serious Backend skills.
Location
City of Bath, UK 🇬🇧
Education
10 plus years* active enterprise development experience and a Fine art degree 🎨
I'm a web developer, graphic designer, type designer, musician, comicbook-geek, LEGO-collector, food lover … as well as husband and father, located just south of Copenhagen, Denmark.
I'm a web developer, graphic designer, type designer, musician, comicbook-geek, LEGO-collector, food lover … as well as husband and father, located just south of Copenhagen, Denmark.
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:
What is the general consensus in the community about referencing elements like this? As opposed to:
Isn't it considered unsafe and error-prone? I don't really remember, it's rarely seen in the wild, perhaps for a reason.
It's best practice to use
document.getElementByIdover the global variable because defining a local variablecolorSchemewould take precedence. It's also annoying to debug these global variables because they are not explicitly defined. When searching for something likecolorScheme =you won't find anything, and finding something likecolorScheme.addEventListenertells you nothing about the type of variable. However, findingdocument.getElementByIdtells you it's a DOM element.I vote that implicit code is dangerous code and explicit code is safe code and there is no grey area 🫣
(see updated feedback above)
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: