Reputation: 51918
Say I have:
<div id='test1'></div>
I want to refer to it simply as:
test1
in code. instead of:
document.getElementById('test1');
$('#test1') // if in jquery
And I don't want to do window.test1 = $('#test1');
I'm looking for a general solution. I know I could probably iterate through all id's with a function on init, but what if dom elements are created dynamically throughout the program. I don't want to run that function that assigns ids to the window every time I add a dom element.
I want test1
(and all id's on the page) to ALWAYS be part of the window object. by default. Is there a way to do this? Like maybe there's a way to inject code when someone tries to access a window object that doesn't exist, and somehow that code will do a document.getElementById
without me having to write it explicitly.
Upvotes: 0
Views: 2929
Reputation: 18557
You can create a Proxy
which translates property accesses to dom lookups.
const dom = new Proxy(window, {
get(_, name) {
return document.getElementById(name);
}
});
dom.test1.style.position = "static"; // tada
Note: don't actually do this
Upvotes: 2
Reputation: 727
You can set a window variable in jQuery as:-
function (elem) {
window['id_' + elem.attr('id')] = elem;
}
elem($("#test1"));
Create a general function to add a window variable everytime a dynamic element is created. But you need to somehow call the function where dynamic variable gets created.
Upvotes: 0
Reputation: 5302
So technically your IDs are actually already exposed as global variables (at least in Chrome). Open the console and try typing out one of your IDs. However, relying on this is a very bad idea.
Consider the scenario where you've got an element called window
. Well, that's not going to be exposed as a global, as it'd conflict with the global window
object.
There are good reasons for being explicit when accessing the DOM, and the cognitive burden you introduce by attempting to make this more convenient will undoubtably bite you later down the line.
Upvotes: 0