HTML X
JS
const images = ["0.jpg", "1.jpg", "2.jpg"];
const chosenImage = images[Math.floor(Math.random() * images.length)];
const bgImage = document.createElement("img");
//HTML에 element추가
bgImage.src = `img/${chosenImage}`;
document.body.appendChild(bgImage); //body 맨 뒤에 추가(prepend는 맨 앞에 추가)
번외 - 넣고 싶은 위치에 element 추가하기
const h2 = document.querySelector("#clock")
document.body.insertBefore(bgImage, h2);
insertBefore()
메소드를 사용bgImage
는 새로운 노드 즉 추가하고 싶은 노드이고 h2
는 참조할 노드h2
요소 앞에 bgImage
가 추가되게 됩니다.이 글은 패스트캠퍼스 노마드코더 '바닐라 JS로 크롬 앱 만들기'을 수강하며 정리한 노트입니다.
https://nomadcoders.co/javascript-for-beginners/lobby