Home > Net >  Getting data to print to a div from innerHTML
Getting data to print to a div from innerHTML

Time:04-10

My goal is to have a div such as: Dog says Bark Bark I have been trying multiple ways but i cant get each pair in the array to output to a div:

const animal = [
    {creature: "Dog", sound: "Bark Bark"},
    {creature: "Cat", sound: "Meow Meow"},
    {creature: "Horse", sound: "Neigh Neigh"},
];

    
function makeSoundFor(animal){
    console.log([animal.creature, animal.sound].join(" "));
    console.log(animal);
}

`document.getElementById("selection").innerHTML = animal;`

export { makeSoundFor };

console.log(animal.map(makeSoundFor));

<!DOCTYPE html>
<html>
    <head>
        <header>Animal Noises</header>
        <style></style>
    </head>

<div id="topline">
    Click on an Animal to play the sound.
</div>
<div id="selection"></div>
<script type="module" src="script.js"></script>
</html>

CodePudding user response:

const animal = [
    {creature: "Dog", sound: "Bark Bark"},
    {creature: "Cat", sound: "Meow Meow"},
    {creature: "Horse", sound: "Neigh Neigh"},
];

animal.map(animal => `${animal.creature} says ${animal.sound}`)

CodePudding user response:

const animal = [
    {creature: "Dog", sound: "Bark Bark"},
    {creature: "Cat", sound: "Meow Meow"},
    {creature: "Horse", sound: "Neigh Neigh"},
];

    
function makeSoundFor(animal){
    return `${animal.creature} says ${animal.sound}`
}

const selection = document.getElementById("selection")

animal.forEach(item => {
    const appendDiv = document.createElement("div")
    appendDiv.innerHTML = makeSoundFor(item)

    selection.appendChild(appendDiv)
})

export { makeSoundFor };
  • Related