Last active
July 18, 2025 10:01
-
-
Save TracyGJG/4c1a65c36259c74aa4d52e93f3c4f620 to your computer and use it in GitHub Desktop.
DOM element reference by
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!DOCTYPE html> | |
| <html lang="en"> | |
| <head> | |
| <meta charset="UTF-8" /> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0" /> | |
| <title>DOM element ref by ($)id</title> | |
| </head> | |
| <body> | |
| <main>Place holder text</main> | |
| <script> | |
| populateMain('test', 'Example Text'); | |
| accessMainElements(); | |
| updateMainElements('test', 'new message'); | |
| function populateMain(id, msg) { | |
| document.getElementsByTagName('main')[0].innerHTML = ` | |
| <div id="${id}">ID: ${msg}</div> | |
| <div id="$${id}">$ID: ${msg}</div>`; | |
| } | |
| function accessMainElements() { | |
| console.log('test:', test.textContent); | |
| console.log('$test:', $test.textContent); | |
| console.log(document.querySelector('#test') === test); | |
| try { | |
| console.log(document.querySelector('#$test') === $test); | |
| } catch (err) { | |
| console.error(err.message); | |
| console.log(document.getElementById('$test') === $test); | |
| } | |
| } | |
| function updateMainElements(id, msg) { | |
| document.getElementsByTagName('main')[0].innerHTML = ` | |
| <div id="${id}">ID: ${msg}</div> | |
| <div id="$${id}">$ID: ${msg}</div>`; | |
| console.log('test:', test.textContent); | |
| console.log('$test:', $test.textContent); | |
| } | |
| </script> | |
| </body> | |
| </html> |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Referenced in my Dev.to post: https://dev.to/tracygjg/just-an-idea-using-a-prefix-with-id-attributes-to-enable-direct-access-3db1