Home > Enterprise >  why is this appearing ?: clone.getElementById is not a function
why is this appearing ?: clone.getElementById is not a function

Time:01-31

I've got this error:

index.js:29 Uncaught TypeError: clone.getElementById is not a function
at HTMLButtonElement.changeImg (index.js:29:11)
changeImg @ index.js:29

It marks the line highlighted. I don't understand why. If somebody can help me I'll appreciate it.

//captura de elementos:
const btn = document.querySelector('.btn');
const templateImg = document.querySelector('.templateImg').content;
const imgContainer = document.querySelector('.imgContainer');

const fragment = document.createDocumentFragment();

let arrayImg = [
"/img/food1.jpg", 
"/img/food2.jpg", 
"/img/food3.jpg", 
"/img/food4.jpg", 
"/img/food5.jpg", 
"/img/food6.jpg", 
"/img/food7.jpg", 
"/img/food8.jpg", 
"/img/food9.jpg"
];

const changeImg = () => {

let ran = Math.floor(Math.random() * 9);
   
//Crear clon del template:
const clone = templateImg.firstElementChild.cloneNode(true);
console.log(clone);
console.log(arrayImg[ran]);
//capturar elemento y modificar el src:
clone.getElementById("img").src = arrayImg[ran];

fragment.appendChild(clone);

   imgContainer.appendChild(fragment);
}

btn.addEventListener('click', changeImg);
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="StyleSheet" href= "style.css"  type= "text/css">
<title>Cambiador de imagenes</title>
</head>
<body>
<div >
    h1>Food and drink in Florianopolis</h1>
    <div ><!--templateImg--></div>
    <button type="text"  id="btn">Change</button>
</div>

<template >
   <img id="img" src="/img/food1.jpg">
</template>

<script src="./index.js"></script>
</body>
</html>

I was trying to change the images inside the template modifying the src:

<template >
    <img id="img" src="/img/food1.jpg">
</template>

When I use querySelector, the error is that the value I try to replace is null even though it's not, and with getElementById, I get that message that it's not a function.

CodePudding user response:

you create a "clone" with this code:

const clone = templateImg.firstElementChild.cloneNode(true);

that is a image element(see in console) and you for changing image src just need to use this code:

clone.src = arrayImg[ran];

CodePudding user response:

getElementById() is a method of document not of any HTML element.

What you want to use instead is querySelector which you can in fact use on elements.

  • Related