Let's see if someone can enlighten
I've been messing around all day with how to change an image when clicking on another using javascript, but when calling an element of the document, it throws me the null value
I have the id = "OneOne" in the image of the HTML document;
When clicking on it, through the onclick event, I send the id of the image and the position it occupies as a parameter, in this case it would be "UnoUno" and "0"
In the function that receives the onclick event I try to reference the image I clicked on to change it to another, and I always receive null
let ele = "#" + elemento; //resultado: "#UnoUno"
let control = document.getElementById(ele); //control: null
I've been with this error for a few hours, I've searched, read, reread and I can't find the error that I'm causing
What am I doing wrong?
Part of the affected HTML file:
<body>
<main>
<section class="section">
<table class="table">
<tr>
<td>
<img id = "UnoUno" class="img" src="./img/reverso.png" alt="imagen11" onclick="abrirImagenClick('UnoUno', '0')">
</td>
</tr>
</table>
</section>
</main>
</body>
Part of the affected CSS file
.table tr td img:hover
{
border: 3px solid #fe0101;
}
.img
{
height: 150px;
width: 110px;
}
Affected part of javascript file
//recibo por parámetro con el evento onclick, el elemento cliqueado y la posición que ocupa
function abrirImagenClick(elemento, posicion)
{
//variable que concatena el elemento con la almohadilla
let ele = "#" + elemento;
//variable que debería de almacenar el elemento del documento donde deseo cambiar la imagen
//pero me devuelve null
let control = document.getElementById(ele);
imagen = document.createElement("img");
imagen.src = "img/" + barajaBarajada[posicion];
//control.appendChild(imagen);
}
getElementById
it expects the tag ID but you add it#
to the beginning so it fails.You must add the
#
when you write a CSS selector. For example the functionquerySelector
does require it.As pointed out in the comments. getElementById does not go with #. But it is also that you don't need to search for the image by the id, since you can send it directly in the event using this