1
<!doctype html>
<html>
<body>
  <img src="..." id="star">

  <script>

    star.onmousedown = function(event) {
      alert()
    };

  </script>

</body>
</html>

Not my code, As you can see above the img with id="star" is being accessed as if it was an object, usually I would expect to do something either like

<img scr="..." onmousedown= myFunction() {...}>

Or

document.getElementById("star").onmousedown = myFunction() {...}

But somehow they just access the img directy via the id, I dont understand the syntax here, is this possible on any element with an id?

EDIT : If so when is there a use for the latter example?? eg. .getElementById(..)

  • I just deleted my answer given that this is a duplicate. Anyway, the important thing is that the ID of an element is a global variable. – Gerardo Furtado Feb 06 '19 at 01:11

2 Answers2

0

You can access the object directly by using the id to reference the object.

star.onmousedown = function myFunction() {...}

Yes, accessing the element directly is possible with any HTML element within the document that has an id attribute set.

guest271314
  • 1
  • 15
  • 104
  • 177
  • @TheMagicalMuffinMan [HTML Standard](https://html.spec.whatwg.org/multipage/dom.html#the-id-attribute) _"The id attribute specifies its element's unique identifier (ID). There are no other restrictions on what form an ID can take.. IDs can consist of just digits, start with a digit, start with an underscore, consist of just punctuation, etc. **An element's unique identifier can be used for a variety of purposes**, most notably as a way to link to specific parts of a document using fragments, **as a way to target an element when scripting**, and as a way to style a specific element from CSS."_ – guest271314 Feb 06 '19 at 01:20
0

Yes you can get any element with an ID using the built-in JS function getElementById(). Read the MDN reference to learn more.

Keno
  • 2,018
  • 1
  • 16
  • 26