DEV Community

Discussion on: The 3 most common DOM selectors

Collapse
 
efpage profile image
Eckehard

It is not recommended, but you can use ID´s without any selector at all:

<h1 id=myhead>Headline</h1>
<script>  "use strict";
    myhead.textContent = "New Headline"
</script>
Enter fullscreen mode Exit fullscreen mode

This is a common standard on all browsers that all ID´s are defined as global variables, so they can be accessed directly or as a property of the window-object ( -> window.myhead.textContent = "test"). It is not recommended to use this method, as the definition only works as long as there is no conflicting definition in the source. This script gives you an error:

<h1 id=myhead>Headline</h1>
<script>  "use strict";
    myhead.textContent = "New Headline";
    let myhead;
</script>
Enter fullscreen mode Exit fullscreen mode

--> "ReferenceError: Cannot access 'myhead' before initialization"

Maybe it´s woth to know...

Collapse
 
ayabouchiha profile image
Aya Bouchiha

Never heard about that, Thank you so much for the information!
Have a nice day!

Collapse
 
efpage profile image
Eckehard

Yes, it is a bit strange feature you should not rely on. There is a global variable for every ID - as long as it is not conflicting with something. In the example above, it is conflicting with a variable, there might be ohter names like classnames etc.. In any case you can access the ID with getElementById without those conflicts.