javascriptgetelementsbyclassname

Javascript - Select div element by its class name and add an image in it


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>

The above code gives an error of Uncaught TypeError: Cannot read properties of undefined (reading '0')...


Solution

  • You need to reference output[0], not document.output[0].

    Also, you need to set the image width="" attribute to 25, not 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>