id in javascript


id property in javascript

What is id 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.

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).
  • A button is created, and a Javascript function is declared in it (fun_name();).
  • When the button is clicked Javascript function is called.
  • In the Javascript function, first we are getting the parent element (document.getElementById("idBtn");) and storing in attr variable.
  • Using the id property, we are getting the id if the element and storing it in elem variable.
  • Next we are displaying the value (alert(elem);).