KnowHow

技術的なメモを中心にまとめます。
検索にて調べることができます。

JavaScriptチートシート6(DOM操作2:ポケモン図鑑)

登録日 :2025/02/09 15:04
カテゴリ :Linux

ポケモン図鑑を表示する
DOM操作でイメージを挿入する
HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="pokemon.css">
</head>
<body>
    <h1>ポケモン図鑑</h1>
    <section id="container"></section>
    <script src="pokemon.js"></script>
</body>
</html>

スタイルシート

.pokemon {
    display: inline-block;
    text-align: center;
}

.pokemon img {
    display: block;
}

Javascript

// https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/1.png

const container = document.querySelector('#container');
const baseURL = "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/"

for(let i=1; i<=151; i++){
    const img = document.createElement('img');
    const pokemon = document.createElement('div');
    const label = document.createElement('span');

    pokemon.classList.add('pokemon');
    img.src = `${baseURL}${i}.png`;
    label.innerHTML=`#${i}`
    pokemon.appendChild(img);
    pokemon.appendChild(label);
    container.appendChild(pokemon);
}