为何出现‘clone.getElementById is not a function’错误?
问题解决:TypeError: clone.getElementById is not a function
错误原因
getElementById 是仅属于document对象的专属方法,你尝试在普通DOM元素(此处的clone是<img>元素实例)上调用它,必然会抛出“不是函数”的错误。
至于你提到用querySelector返回null,是因为clone本身就是模板里的<img>元素,你再用clone.querySelector('#img')去它的子元素中查找id为img的元素,而<img>没有子元素,所以返回null。
修正代码
直接修改clone的src属性即可,因为clone就是你要操作的目标<img>元素:
const changeImg = () => { let ran = Math.floor(Math.random() * 9); // Crear clon del template: const clone = templateImg.firstElementChild.cloneNode(true); // 直接修改clone的src,clone就是目标img元素 clone.src = arrayImg[ran]; fragment.appendChild(clone); imgContainer.appendChild(fragment); }
另外注意你的HTML存在一处语法错误:<h1>标签未闭合,正确写法应为<h1>Food and drink in Florianopolis</h1>,否则会导致页面结构异常。
额外优化建议
- 将随机数上限改为数组长度,避免硬编码数字:
Math.floor(Math.random() * arrayImg.length),后续增减图片无需修改此处代码。 - 如果每次点击只需显示一张新图片而非追加,可在添加新图片前清空容器:
imgContainer.innerHTML = '';
内容的提问来源于stack exchange,提问作者D B
相关产品推荐
相关产品推荐

