HTML element is represented in JavaScript as a global variable , How? [duplicate] - javascript

This question already has answers here:
Do DOM tree elements with IDs become global properties?
(5 answers)
Closed 6 years ago.
Does JavaScript represent each HTML element as a global variable which name is the id of the element ?
Let's say I have a hidden input element like this:
<input type="hidden" value="10" id="myInput" />
so I can access it in JavaScript :
console.log(myInput.value);
I tried it in chrome and firefox, and it worked for me.
My question is :
Is this issue new in JavaScript ?
Is it the best practice to get an element by id ?
Why they implement this functionality although using global variables is not the best practice?

That is called as named access. Every element which has an id will be referenced in global scope. That is the window object. Even though it is not a good practice to use it, it is standardised with HTML5.
A simple conflicting case for its usage is,
If you declare a variable in global scope like hide, and also you are having an element in your document with id hide. Then that element reference will be overridden by our global variable. At that time, if you use it(element reference) in any event handler or somewhere, it will results in error.

Related

Is it appropriate to handle an element by its ID (as a var) without getElementById? [duplicate]

This question already has answers here:
Do DOM tree elements with IDs become global properties?
(5 answers)
Why don't we just use element IDs as identifiers in JavaScript?
(5 answers)
Closed 2 years ago.
I've been coding with vanilla JS for quite a few years, but whenever I needed to handle an HTML element with an id attribute I'd reasonably resort to:
var myId = document.getElementById('myId');
When, by mere accident, I actually found out that this works:
function add() {
let span = document.createElement('span');
span.innerHTML = '<br />o hi';
// === THIS: ===
correctId.appendChild(span);
}
<div id="someId"></div>
<input type="button" value="MOAR" onclick="add()" />
<div id="correctId"><strong>Append here: </strong></div>
<div class="someClass"></div>
I was beyond shocked to learn this.
The million dollar question is... Is that even good practice or standard at all? Can I safely use that in my code or is it a very recent addition, deprecated, browser-specific or even dangerous?
I didn't even know how to look for references on this behavior. I tried looking for "element id as variable", "using ids as var names" and so on. Nothing. Everywhere I go people mention document.getElementById(), document.querySelector('#'), jQuery, but never that one behavior - that elements with an id attribute are already available as variables in JavaScript, or at least that's how I understood it.
I'm using Chrome 81.0.4044.138. Can anyone please shed any lights on this?
I don't see any problem with this. All you are doing is getting the reference in an indirect way and then adding it using inner Html. I am no expert but do this all the time.

Which is faster in jquery: $("selector") or selector as an object variable? [duplicate]

This question already has answers here:
Is storing jQuery elements in variables more efficient?
(5 answers)
Closed 3 years ago.
Can anyone explain if using the object variable selector offers better performance compared to the traditional $("#selector") in jQuery?
<form id="my_form" action="www.test.com" method="POST">
<input type="text" id="name">
<button type="submit" class="" style="">SEND</button>
</form>
$(document).ready(function() {
var my_form = $("#my_form"); // object variable selector
my_form.trigger("reset");
// or
$("#my_form").trigger("reset");
});
Let's just say that I will be using the $("#my_form") more than ten times to manipulate the child elements in the DOM.
Is it better if just store the selector as an object variable for better performance or it doesn't make a difference?
If you're going to be re-selecting the same element multiple times, then storing the jQuery object in a variable is always much faster as it negates the need to read data from the DOM, which is comparatively much slower.
I don't know about performances but as #Rory McCrossan said its supposed to be faster to store it.
And for maintenance, if you needs to modify it, as you use it several times, it's better to store. Then you'll need to modify the value only one time

What's the difference between "object.property" and "document.getElementById().property" [duplicate]

This question already has answers here:
Do DOM tree elements with IDs become global properties?
(5 answers)
Closed 5 years ago.
I have this HTML:
<input id="foo">Hello world!</input>
I wonder what the difference between
document.getElementById('foo').value
and
foo.value
is in the Javascript
foo.value takes advantage of the global variable foo that is created when an element has an id established for it. Both versions access the same object and work with the same data.
Accessing an element with just the id has been around since the beginnings of JavaScript and remains today, but over time the Document Object Model API was created to have a more robust and complete way of interacting with documents.
Having said this, document.getElementById() is the more modern approach. It's part of the Document Object Model API standard and is generally recommended as it is clearer and provides many ways to interact with elements in a web document.
Here's an example.
console.log(div.innerHTML);
div.innerHTML = "New Content!";
console.log(document.getElementById("div").innerHTML);
<div id="div">This is an element</div>

In Java Script Global Variable is not clear [duplicate]

This question already has answers here:
How can I unset a JavaScript variable?
(12 answers)
Closed 7 years ago.
I have declare global variable in java script, i try to clear with following code but it not clear.
As i defined global variable.
var usno;
then before set value i tried following code
delete window.usno;
usno = undefined;
usno=null;
but no success.
Please help on this
Thanks
Basit.
In short, you cannot delete variables defined with var. If you set the variable using window.usno then it can be. See Understanding delete and the answers to How to unset a JavaScript variable? for more details.
Do you really need to delete the variable though? Instead of making a global variable, restrict the scope of your variable to a function so that it will be garbage collected after the scope of the function ends.
Your first solution is the correct one.
delete window.usno;
That deletes the property usno from the global window object. But here is where the confusion lies, when we test it:
window.usno; // -> undefined
So, a deleted or non-existent property returns undefined. Thus, in effect, the following two statements achieve much the same thing:
delete window.usno;
window.usno = undefined;
They are not exactly the same thing. In the second case, the usno property still exists, as you will find if your iterated through all of the properties of window.
Short answer:
delete window.usno;

Access a DOM element by using its id as var [duplicate]

This question already has answers here:
Do DOM tree elements with IDs become global properties?
(5 answers)
Closed 8 years ago.
I just came across this by accident and I want to check if this is actually supposed to happen.
I have a div in my page with id box. In my Javascript I set a style to a variable named box: box.style.webkitTransform = "yadda yadda".
I thought that box was in scope, declared as var box = document.getElementById('box');, but it is not (the declaration is in another function!). Neither is there a var box defined globally or in any other place.
However the style got assigned just fine. So somehow the elements' id can be used globally in Javascript? Convenient, but I'm afraid to use it. I assume if the name is used for an actual variable it will override this behavior.
Some browsers add 'named elements' as properties of the document or windowobject. See this SO-question, especially the excellent answers from bobince

Categories