I am trying to get the value from a div pressed. It works if I use id but not class, and I don't want to spam the same line with minor differences. I want to keep the code minimal and I am new to js.
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript">
function test(){
var ai = document.getElementsByClassName('h').getAttribute('value');
alert(ai)
}
</script>
</head>
<body>
<div style="height:100px;width:100px;background-color:red;" class="h" value="1" onclick="test()">1</div>
<div style="height:100px;width:100px;background-color:red;" class="h" value="2" onclick="test()">2</div>
</body>
</html>
getElementsByClassName returns a nodelist. To retrieve some value for the clicked element, pass this to the function call. Also value only works with input elements. To get the value property from a div, use getAttribute("value").
function test(el) {
alert(el.getAttribute("value"));
}
<div style="height:100px;width:100px;background-color:red;" class="h" value="1" onclick="test(this)">1</div>
<div style="height:100px;width:100px;background-color:red;" class="h" value="2" onclick="test(this)">2</div>
You can use event object to realize which element has pressed (event.target), then get any attribute from the pressed element.
function test(event) {
const value = event.target.getAttribute('value');
alert(value)
}
<div style="height:100px;width:100px;background-color:red;" class="h" value="1" onclick="test(event)">1</div>
<div style="height:100px;width:100px;background-color:red;" class="h" value="2" onclick="test(event)">2</div>
Another possibility is to use an event handler. You no longer need the click event in your HTML element.
var elems = document.querySelectorAll(".h"); //Get all elements with class "h"
elems.forEach(function(el) {
el.addEventListener("click", function() { //Add Event Listener to element
alert(this.getAttribute("value")); //Read and output attribute
})
});
<div style="height:100px;width:100px;background-color:red;" class="h" value="1">1</div>
<div style="height:100px;width:100px;background-color:red;" class="h" value="2">2</div>