Explain Codes LogoExplain Codes Logo

Best Practice: Access form elements by HTML id or name attribute?

html
accessibility
best-practices
responsive-design
Nikita BarsukovbyNikita Barsukov·Jan 15, 2025
TLDR

Employ the id for direct, unique interactions with DOM elements and fine-tuning styles; leverage the name for grouping form components in anticipation of form submission.

// Jedi trick to manipulate element by ID: document.getElementById('elementId').style.color = 'red'; // Just a bunch of clones grouped by 'name' attribute: <form><input name="cloneTroopers" type="radio" value="1"></form>

In essence, id is your keen sniper, while name is your efficient field marshal.

The Power of Direct References

Using the Force with document.getElementById()

Obi Wan Kenobi prefers a precise strike. Be like him. With document.getElementById("myform").elements, he accesses form elements more accurately and swiftly. It's standard-adherent and ready for the browser updates of tomorrow.

// Jedi trick to access input via ID: let forceField = document.getElementById("myform").elements["lightSaber"];

Accessibility: The Right Path

The for attribute and the id attribute are a powerful duo in the accessibility world.

// Talk about perfect pair, like Han Solo and Chewbacca: <label for="quizAnswer">Answer</label> <input id="quizAnswer" name="quizAnswer" type="text">

Code flexibility: Evolving like the Sith

Choose your app to be flexible, like this, a shape-shifter that refers to the right context.

function forceSensitiveFunction() { // 'this' could be your greatest ally or worst enemy let SithOrJedi = this.value; }

Avoiding Dependencies: Choose the Light Side

In coding, one should not be quick to rely on the Dark Side (i.e., unnecessary libraries). A minimalistic approach will bring peace to your galaxy.

The Philosophy of Modularity

Like the eternal balance of the Force, modularity plays a crucial role. Master the art of passing identifiers to functions.

function signInToDeathStar(formId, inputName) { return document.getElementById(formId).elements[inputName]; }

Redundancy: The Clone Trooper's Way

Sometimes, like an army of Clone Troopers, having many of the same kind (both id and name) assists in completing the mission.

Adapting Strategy: The Jedi Council's Way

If the Council moves the meeting to a different room, would you be prepared? Yes, with adaptable access methods like querySelector.

// Selecting by name even when the Council is playing hide-and-seek: let councilMember = document.querySelector('#jediCouncil [name="Yoda"]');