Languages
[Edit]
EN

JavaScript - get element id attribute

3 points
Created by:
Inayah-Alexander
767

In this article, we would like to show you how to get the element id attribute using JavaScript.

Quick solution:

var id = element.id;

or:

var id = element.getAttribute('id');

 

Practical examples

1. id property solution

In this example, we use embedded id property that returns the element id attribute value.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <button id="element-1" onclick="printId(this)">Display id attribute value</button>
  <button id="element-2" onclick="printId(this)">Display id attribute value</button>
  <script>

    function printId(element) {
        var id = element.id;
        console.log(id);
    }

  </script>
</body>
</html>

2. getAttribute() method solution

In this example, we call getAttribute('id') method that returns the element id attribute value.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <button id="element-1" onclick="printId(this)">Display id attribute value</button>
  <button id="element-2" onclick="printId(this)">Display id attribute value</button>
  <script>

    function printId(element) {
        var id = element.getAttribute('id');
        console.log(id);
    }

  </script>
</body>
</html>

 

References

  1. Element.getAttribute() - Web APIs | MDN
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join