EN
JavaScript - get element id attribute
3
points
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>