No entiendo qué estoy haciendo mal aquí, trato de depurar el código, pero no encontré lo que hice mal aquí. Traté de reemplazar la imagen en html con el uso de java script, agradecería alguna ayuda útil para mi problema
Código HTML:
<img id = "lamp" src = "js/Capture.PNG"/> <!--make a button to turn on or off the lamp in this case --> <button id = "off" name = "offf" onclick="change_attribute()" >Turn off the light</button> <button id = "on" name = "offf" onclick="change_attribute()"> turn on the light </button>código JavaScript:
function change_attribute() { var x = document.getElementsByName("offf"); if (x.id === "off") { document.getElementById('off').src = "js/Capture.PNG/"; } else { document.getElementById('on').src = 'js/Capture2.PNG/' } } function change_attribute(e) { if (e.target.id === "off") { document.getElementById('lamp').src = "https://cdn-icons-png.flaticon.com/512/2910/2910914.png"; } else { document.getElementById('lamp').src = 'https://cdn-icons-png.flaticon.com/512/702/702797.png' } } #lamp{ width: 50px; height: 50px; margin-right:15px; } <img id="lamp" src ="https://cdn-icons-png.flaticon.com/512/2910/2910914.png"/> <!--make a button to turn on or off the lamp in this case --> <button id="off" class="lightBtn" onclick="change_attribute(event)" >Turn off the light</button> <button id="on" class="lightBtn" onclick="change_attribute(event)"> turn on the light </button>El método getElementsByName( ) devuelve una colección de todos los elementos del documento con el nombre especificado. está tratando de hacer referencia a una propiedad de id que no existe en la matriz sino en los elementos reales de la matriz.
Probablemente debería refactorizar su código para usar un solo elemento html que llame a change_attribute() y alternará el estado respectivamente entre activado y desactivado.
getElementsByName() devuelve una matriz de elementos HTML que especifica la condición dada.
En su condición, obtiene una matriz de elementos html de botones como resultado de lo cual, cuando accede a x.id , aparece un error ya que x es una matriz, en lugar de un objeto.
intente refactorizar su código y llame a change_attribute desde un solo lugar