Is using ID as a global variable a good practice in JAVASCRIPT?

Asked

Viewed 132 times

6

I discovered that there is a new way to rescue and define values to any HTML tag, using its ID as a variable:

<html>
<head>
  <title>Meu Teste</title>
</head>

<body>

  <input id="testeVariavel">

</body>
</html>

JAVASCRIPT

/*1- Utilizando o ID da TAG como variável*/
testeVariavel.value = "teste"


/*2- Forma tradicional*/
var testeVar = document.querySelector('#testeVariavel');
testeVar.value = "teste 2"

I wonder if it is a good practice to use the first way I exemplify in the code above Javascript, as I saw that this is much more practical than the normal method (since I can even work with functions).

Both demonstrated ways, I can define any value for my input, but saving on the code and leaving "apparently" more optimized.

I have some future impact by using this more practical way as it is very similar to a global variable as well, because in theory I can access the element whenever I want to set or redeem a value.

  • 1

    The ID was made to anchor objects, when you use as a tag, you are disconnecting from the anchored element, so I believe it has nothing to do with good or bad practice, but what the expected result.

1 answer

4


Access the element from the first way (specification link) may generate some conflicts of the type:

console.log(typeof teste);
console.log(typeof (document.getElementById('teste')));
<div id="teste"></div>
<script>
    function teste() { /* ... */ }
</script>

Note that both the element id value and function name are equal. This may generate bugs in your application since at some point you would expect that teste is a reference to the div and not the function. Note that the problem does not occur if you use for example the getElementById.

This is a very simple example, but imagine that a simple typo can cause this kind of conflict.

Another problem is with the old IE, which causes the attribute value name elements within a form are made available on window.

So in my opinion it’s not good practice.

  • Thank you Marcelo! Your explanation is quite complete, I could understand. Using your example of typing, it makes sense if it is something very complex that is under development and now with this explanation and example link I don’t really see how a good practice to use this simpler method. Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.