holy3425234
holy3425234

Reputation: 11

Naming conventions - HTML elements in JS

How do I name the HTML element objects in JS?

var divEditorArea = document.getElementById("editorarea");

var btnCheckSyntax = document.getElementById("checksyntax");

Is this a good way?

Upvotes: 0

Views: 2532

Answers (2)

Gideon Babu
Gideon Babu

Reputation: 356

If you use vanilla JS, as Vinicius told there is no convention for naming JS variables for HTML DOM elements.

I would name them as:

let elCheckSyntax = document.querySelector("#checksyntax");

OR

let elementEditorArea and elementCheckSyntax

another way would be some team like to prefix the DOM elements with $. So as soon as anybody in the team sees any variable prefixed with $ they know it's a DOM element.

like this

let $editorArea;
let $checkSyntax;

so, it totally depends on your convenient if you work independently and your team's naming convention

Upvotes: 1

Vinicius Teixeira
Vinicius Teixeira

Reputation: 51

To my knowledge, there is no convention for naming HTML elements in JS. Javascript is such a diverse world that even if there was a convention, it would hardly be followed by the majority of the community. See, for example, the variety of code linters and code style conventions there are (https://www.sitepoint.com/comparison-javascript-linting-tools/).

Names should show your intentions clearly, so that code is easily understandable. I don't think that adding the type of the HTML element to the JS variable names is of much use for clarity purposes (the 'btn' and 'div' in you example), but there could be cases where it adds clarity. And, if you are in a team, you probably should follow the team's conventions.

Use your best judgement and always strive for clarity in your code.

Upvotes: 1

Related Questions