Estoy tratando de obtener el valor de un div presionado. Funciona si uso id pero no class, y no quiero enviar spam a la misma línea con pequeñas diferencias. Quiero mantener el código mínimo y soy nuevo en 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 devuelve una lista de nodos. Para recuperar algún valor para el elemento en el que se hizo clic, páselo a this llamada de función. Además, el value solo funciona con elementos de entrada. Para obtener la propiedad de value de un 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>Puede usar el objeto de evento para darse cuenta de qué elemento ha presionado (event.target), luego obtener cualquier atributo del elemento presionado.
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>Otra posibilidad es utilizar un controlador de eventos. Ya no necesita el evento de clic en su elemento HTML.
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>