You are not logged in.

#1 2021-08-22 13:41:19

Trilby
Inspector Parrot
Registered: 2011-11-29
Posts: 29,452
Website

[SOLVED] JS: browser support for direct referencing of element ids

I'm curious about browser support for a capability that JS seems to have at least in the browsers I'm using.  But I've not been able to look it up as I've not found any search terms that lead to any references to this behavior.  But as seen in the example html page below, I am able to reference the div with the id "mydiv" simply as an object `mydiv` in the js code:

<html>
<head>
<title>Test js id access</title>
</head>
<body>
<div id="mydiv">Hello World!</div>
<script>
mydiv.onclick = function() { mydiv.append(" Hi!"); }
</script>
</html>

All documentation and tutorials I can find suggest that one should have to do something like the following in js before the above code should work:

var mydiv = document.getElementById("mydiv");

Is the fact objects with element id names seem "prefilled" on my browser a quirk or non-standard feature?  Or is this (coming to be) expected on most browsers?

EDIT: perhaps asking if it is "non-standard" is the wrong phrasing, because - unless I'm totally missing it - this behavior is most definitely not codified in the relevant standards.  So a better word might be "rare": is this an oddity of my browser, or is a common non-standard behavior among modern browsers?

Last edited by Trilby (2021-10-18 13:16:06)


"UNIX is simple and coherent..." - Dennis Ritchie, "GNU's Not UNIX" -  Richard Stallman

Offline

#2 2021-08-22 14:28:28

seth
Member
Registered: 2012-09-03
Posts: 50,012

Offline

#3 2021-08-22 17:04:01

porcelain1
Member
Registered: 2020-01-18
Posts: 97

Re: [SOLVED] JS: browser support for direct referencing of element ids

In addition, I first heard about this here: https://javascript.info/searching-elements-dom but it states right away not to use it. And as mentioned in seth's links, it is standardized but just for bug compatibility and thus not recommended.


Behemoth, wake up!

Offline

#4 2021-08-22 18:03:16

Trilby
Inspector Parrot
Registered: 2011-11-29
Posts: 29,452
Website

Re: [SOLVED] JS: browser support for direct referencing of element ids

Thanks!

It turns out it is in some standard and I hadn't found it.  For my current use case it seems perfectly reasonable to use as I am writing all the html and js (and a tiny web server too) myself.  There is no other web content that will interact with this at all.  So I'll enjoy the convenience knowing that it should be expected to work on other browsers.


"UNIX is simple and coherent..." - Dennis Ritchie, "GNU's Not UNIX" -  Richard Stallman

Offline

Board footer

Powered by FluxBB