id in javascript

id property in javascript

id property is an identifier, used to represent an element.

id must be unique in an document.

It can be retrieved using getElementById method.

It can also be used as a selector to set CSS property.

Example - Get id value of an element

Try Yourself

Example Explanation

  • In the above example we have created a button (Get id value).
  • When the button is clicked, fun_name() function is called.
  • In the Javascript function, first we are getting the element (document.getElementById("idBtn")) and storing it in attr variable.
  • Using the id property, we are getting the id of the element and displaying it (alert(elem)).