Getting id in js | Sololearn: Learn to code for FREE!

+6

Getting id in js

Hello everybody. I came accross a problem Why I don't need to get the element by id in js and can directly use the id in js and don't get any error? https://code.sololearn.com/W9wPXCuvrHLE/?ref=app

js

1/18/2022 7:35:25 AM

Zeynab

10 Answers

New Answer

+1

If you name an element in your HTML document using the id attribute, and if the Window object does not already have a property by that name then the id is created by default as property of global object , and  the Window object is given a property whose name is the value of the id . That's the reason why you can use the id without using getElementById

+2

click.innerHTML

+2

IDs of elements are registered as global variable. Some say this was Chrome specific, so I'm not too sure whether all browsers shows such behaviour. https://dev.to/vuelancer/dom-element-id-as-global-variable-1l2n https://2ality.com/2012/08/ids-are-global.html

+2

Ipang thanks great info🙏🏽

+1

Cuz you have used onclick https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onclick https://www.w3schools.com/jsref/event_onclick.asp

+1

Even i delete onclick event and use set interval to change the divs text i still dont need to get element by id in js and can directly use the id in js🤔

+1

Interesting enough if i get the element by id in js i get an error😅

+1

ㅤㅤㅤ change the click to clickme Still the same problem

+1

Shubham Yadav oh interesting, so that's the reason why it gives error when i try to get the id in js and store it in the same name as the id in html

-1

1st write <input id='name' type="text"> in HTML & then use getElementById('name'); in js to get the id which you specified in your html code