I'm gonna be the BEST.

[JS] js로 element 생성한 후 html에 추가하기 (createElement, appendChild) 본문

프론트엔드/JavaScript

[JS] js로 element 생성한 후 html에 추가하기 (createElement, appendChild)

새싹 개발자 뚜비 2022. 9. 10. 22:36
728x90

[ 노마드코더 학습 기록 ]

바닐라 JS로 크롬 앱 만들기(6.1 Background)


momentum 크롬앱은 배경화면이 랜덤으로 바뀐다. 

랜던 배경화면을 만들어보자 !

 

이미지 출처: 그라폴리오_ ohjn96 작가님

먼저 JS 폴더안에 background.js 파일을 만들어주고 html에서 import 시켜준다.

그리고 img폴더 생성 뒤 원하는 이미지를 넣어준다.

이러면 준비는 끝났다.

 

랜덤 배경화면 작업은 랜덤 명언과 작업과 거의 같다고 볼 수 있다.

const images = ["0.png", "1.jpeg", "2.jpg", "3.png", "4.jepg"];

const chosenImage = images[Math.floor(Math.random() * images.length)];

console.log(chosenImage);

먼저 images Array를 만들고 이미지들은 담아준다.

이미지 파일 이름과 반드시 같아야 한다.

 

그리고 지난 랜덤 명언 만들기 때 썼던 코드를 가져와서 복붙해준다.

Math.random으로 나온 숫자를 images 길이의 숫자와 곱해준 다음 Math.floor로 반내림 해주는 것이다.

 

그리고 console.log로 찍어서 확인해보자.

 

새로고침 할때마다 랜덤으로 이미지명이 바뀌게 된다.

 

 

자 이제 그럼 이미지를 html에 실제로 추가해보도록 하자.

지금까지는 html에서 먼저 작성한 후 js를 가져오는 것이었지만

이번에는 js에서 생성해낸 것을 html에 추가하는 것이다.

 

const images = ["0.png", "1.jpeg", "2.jpg", "3.png", "4.jepg"];

const chosenImage = images[Math.floor(Math.random() * images.length)];

const bgImage = document.createElement("img");

console.log(bgImage);

js가 Element를 생성하고 그걸 html에 뿌려줘야하기 때문에

createElement를 이용한다.

결과값을 console.log로 확인해보자.

 

그냥 <img> 라고 뜨는 것을 알수있다.Elements 탭에서 보려고 하면 어디에도 없다.

페이지에서 찾을 수가 없다는 뜻이다.하지만 img는 존재한다.

 

const images = ["0.png", "1.jpeg", "2.jpg", "3.png", "4.jepg"];

const chosenImage = images[Math.floor(Math.random() * images.length)];

const bgImage = document.createElement("img");

bgImage.src = `img/${chosenImage}`;

console.log(bgImage);

bgImage.src도 쓸 수 있다.

``백틱을 이용하여 chosenImage를 추가해서 string을 만든다.

그리고 console.log를 해보자.

 

ERR_FILE_NOT_FOUND

에러가 발생했는데 이건 오타때문에 난 에러다.

확장자명이 jpeg인데 jepg라고 적어서 난 오류였으므로 다들 오타를 조심하자!

ㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋㅋ

 

오타 수정 후 잘 작동된다.

이게 바로 js에서 html element를 생성한 것이다 !

 

이제 마지막으로 bgImage를 html body에 추가해주면 된다.

const images = ["0.png", "1.jpeg", "2.jpg", "3.png", "4.jpeg"];

const chosenImage = images[Math.floor(Math.random() * images.length)];

const bgImage = document.createElement("img");

bgImage.src = `img/${chosenImage}`;

document.body.appendChild(bgImage);

document.body.appendChild(bgImage);를 이용하여 html body에

js로 만든 element인 bgImage를 추가한다.

 

새로고침하여 확인해보면 img src로 랜덤한 이미지가 추가된 것을 알수있다.

멋져 멋져😎

 

이미지 조정이 필요하겠지만 대문짝만하게 랜덤한 사진이 잘 들어갔다 !!

ez ez

 

랜덤사진 넣기 끝!

728x90