What exactly is the function of the id attribute of an element in HTML and why it can be used directly?

what is the use of the id attribute set in the HTML tag, and why can I access the element directly with the id value?

< hr >

as follows:
I set id= "text"
on a textarea I can directly use text as a variable, the same as document.getElementById ("text") . Why?
so I can call the element directly using the id value in js ?
solve.

Apr.07,2021
As specified by the W3C

, the id attribute is unique and can be accessed directly, but in order to prevent variable conflicts, it is generally necessary to get the element through document.getElementById (). Hope to adopt


HTML DOM mainly defines three ways to find elements. In addition to document.getElementById (), there are also document.getElementsByName () and document.getElementsByTagName (), document.getElementById () methods that return a reference to the first object of the specified ID.


  1. id is the ID card of the html element = > is unique in the same page and cannot be duplicated
  2. "ID card" is not equal to the element itself, so in theory, you can't get the element only by using id value. If you want to get an element reference, you need to use document.getElementById (), to find it for me through "ID card"!
  3. You can get it in the
  4. question because the browser makes a transformation of id and copies the corresponding object to the window.id name = document.getElementById (id name)

accessing directly with id is a feature left over from the old version of js. Browsers create the id property of the window instance in order to be compatible with the old web pages.

therefore do not rely on this feature, which may fail if it contains special characters or conflicts with other properties of the window instance. It is safer to use document.getElementById .

as for the role of id, other answers also say that it is used as a unique identity of the element to be easily called in js, or styled with CSS.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1ea12a7-47909.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1ea12a7-47909.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?