51

Accessing Element IDs in DOM as window/global variables

 5 years ago
source link: https://www.tuicool.com/articles/hit/UV7vqm3
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
uU7bquB.jpg!webJzmu2yY.jpg!web

D uring my early web development days, element IDs was one of the first things I learned on how to manipulate elements from JS land. With reference to elements by their IDs

<div id="so_many">So many to think about</div>
<script>
    const so_many = document.getElemntByID('so_many')
</script>

we can:

1: change the inner html of the element (innerHTML)

<div id="so_many">So many to think about</div>
<script>
    const so_many = document.getElemntByID('so_many')
    so_many.innerHTML = "I'm flying without wings"
</script>

2. change the style of the element

<div id="so_many">So many to think about</div>
<script>
    const so_many = document.getElemntByID('so_many')
    so_many.style.backgroundColor = "green"
</script>

3. append a child node to the element

<div id="so_many">So many to think about</div>
<script>
    const so_many = document.getElemntByID('so_many')
    so_many.appendChild(document.createTextNode('my text'))
</script>

4. remove the element from the browser node

<div id="so_many">So many to think about</div>
<script>
    const so_many = document.getElemntByID('so_many')
    const textNode = document.createTextNode('my text')
    so_many.appendChild(textNode)
    so_many.removeChild(textNode)
</script>

5. attach and remove event listeners to the element.

<div id="so_many">So many to think about</div>
<script>
    const so_many = document.getElemntByID('so_many')
    so_many.addEventListener('focus', (evt)=> {
        //.. code here
    })
    so_msny.removeEventListener('focus')
</script>

* so many etc

Now things are about to change for real.

Element IDs in the window object

I recently learned that element IDs are stored as global variables or window variables.

what does it mean?

It means that if we create elements assigning them id attributes, that the id attributes can be accessed via the window object or as a global variable.

Let’s say we have this:

<div id="so_many">So many to think about</div>

This is an HTMLDivElement element with an id attribute of value so_many . Now, this HTMLDivElement can be accessed via the so_many in the window object:

<script>
    log(window.so_many)
</script>
nUnuMbF.png!webFzmQNj6.png!web

or as a global variable (like all window properties):

<script>
    log(so_many)
</script>
nUnuMbF.png!webFzmQNj6.png!web

This variable refers to the instance of the elements. Just like doing:

<div id="so_many">So many to think about</div>
<script>
    const _so_many = document.getElemntById('so_many')
</script>

The variable so_many in window is the same as _so_many both refers to the same instance of the div element HTMLDivElement <div id="so_many">So many to think about</div> . We can manipulate the <div id="so_many">So many to think about</div> using both window.so_many and _so_many . Its like the browser have already done this document.getElemntById(...) for us.

With the element IDs in the window variable we can manipulate the DOM elements:

<div id="so_many">So many to think about</div>
<script>
    // const so_many = document.getElemntById('so_many')
    const textNode = document.createTextNode("Some Text")
    window.so_many.appendChild(textNode)
// or as global variable
    so_many.appendChild(textNode)
</script>
iIbQbeJ.png!webAnqaI3z.png!web

See we commented out the // const so_many = document.getElemntById('so_many') , yet we were able to access the element via the Id name so_many in the window object(or as a global variable) and append a text node to it.

They are even accessible in DevTools console:

>> so_many
<- > <div id="so_many">So many to think about</div>
>> so_many.appendChild(document.createTextNode("Some text from console"))
qauuiqJ.png!webAje2iiq.png!web
VJBFreE.png!webyqeuieV.png!web

Attaching event listeners

>> so_many.addEventListener('click',(evt)=>alert('from console'))
rmYJBvN.png!webyeqUF3E.png!web

If we click on the div element we will get:

7zYNJ3a.png!webJRnyEzm.png!web

Change the style of the element

>> so_many.style.backgroundColor = "green"
3i6B3yM.png!webeYNnUrB.png!web

See our background color is white, the above code will change it to green. Hit Enter:

FFJJ73u.png!webyUFzMzR.png!web

The background color changes to green.

Change the HTML of the element

>> so_many.innerHTML = "<b>Inner HTML from Console</b>"

Before:

Vv6ruqB.png!webV3IJbua.png!web

After we hit Enter:

maamMvZ.png!webEZb2y2j.png!web

You see its fun. You can play with other HTMLElement methods to see how to manipulate element by their IDs through the window or global variable without the document.getElementById(...) overhead.

Conclusion

This is good!!! I think I’ll stop writing document.getElementById(...) in my next projects :). Sometimes they seem to long to write and I feel lazy sometimes when writing long method names :)

But, we should be very careful when using window or global variable to access our elements via their IDs, we should use this feature interactively, not rely on it in actual code — Advice from Dr. Axel Rauschmayer .

If you have any question regarding this or anything I should add, correct or remove, feel free to comment, email or DM me. Thanks for reading :smiley:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK