代码之家  ›  专栏  ›  技术社区  ›  darkchampionz

Javascript-根据类名选择div元素,并在其中添加一个图像

  •  -2
  • darkchampionz  · 技术社区  · 3 年前

    let output = document.getElementsByClassName("one");
    
    const img = document.createElement("img");
    img.src = "https://www.gravatar.com/avatar/4581a99fa5793feaeff38d989a1524c6?s=48&d=identicon&r=PG";
    img.width = "25px";
    document.output[0].appendChild(img);
    .one {
      border: 2px solid red;
    }
    <div class="one">Test</div>

    上面的代码给出了一个错误 Uncaught TypeError: Cannot read properties of undefined (reading '0') ...

    1 回复  |  直到 3 年前
        1
  •  3
  •   jkrei0 Richard Henage    3 年前

    你需要参考 output[0] document.output[0] .

    此外,您需要设置图像 width="" 把某事归因于某人 25 25px .

    let output = document.getElementsByClassName("one");
    
    const img = document.createElement("img");
    img.src = "https://www.gravatar.com/avatar/4581a99fa5793feaeff38d989a1524c6?s=48&d=identicon&r=PG";
    img.width = "25";
    output[0].appendChild(img);
    .one {
      border: 2px solid red;
    }
    <div class="one">Test</div>