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
Related
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.
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>
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.
This question already has answers here:
var self = this?
(8 answers)
Closed 7 years ago.
So I have something like
this.editElement = $("<a href='#'>Edit</a>").click(function() {
this.startEdit();
});
This however takes "this" to be the editElement itself, rather than the parent object.
I've managed to get it to work by making a
var parent = this;
before setting click and then using parent enough of this.
Is this the correct way to solve the problem?
That's a very correct way, yes, and it's common.
You also took the right decision in naming it parent instead of the semantic-less _this we often see.
Other solutions :
to bind the callback to the external this
to use the data argument of JQuery's on to pass the parent
to dynamically find the parent from the callback
but most often referring to a variable kept in the external closure as you did is the cleanest solution.
This question already has answers here:
Do DOM tree elements with IDs become global properties?
(5 answers)
Closed 9 years ago.
I noticed the following:
<div id='myDiv'>...</div>
<script>
myDiv.style.color = 'red'; // I can access the object.
<script>
Before realizing this, I was always using the following:
var x = document.getElementById('myDiv');
x.style.color = 'red';
I am confused. What's the point of the second approach? Does the first approach always work?
Are IDs for an html element always available from the window object?
No. It is a non-standard Microsoft-ism that some other browsers have adopted for compatibility reasons. It is prone to namespace collisions, and not completely cross-browser compatible: don't do it.
What's the point of the second approach?
It is standard, well-supported cross-browser (and also cross-language).