I've searched and searched but I've only found solutions to .join() the items into a single string..
const createCard = () => {
const pokemonTypes = ['grass', 'fire', 'water'];
return (
`<div>
${pokemonTypes.map(type => `<div>${type}</div>`)}
</div>`
)
}
document.body.insertAdjacentHTML("beforeend", createCard());
For some context, I am using an API but I simplified the code so it's quick and easy to read.
I am trying to display each string into its own div so that I can style each div separately...like color coded buttons: green for grass, blue for water, red for fire etc.
When I run the code the strings successfully display in their own div, however the comma remains. I'd like them to just display next to each without the comma separating them.
CodePudding user response:
Array.map returns an array as the output. Setting this array as the html content is same as casting an array to a string.
Example
const numArray = [1, 2, 3];
console.log(numArray.toString());
Casting an array to a string will always includes the comma in between.
Your expression is same as below one
document.body.insertAdjacentHTML("beforeend", [1, 2, 3]);
What you have to do is you have to join this array with empty string and set this single string as the html contant as below.
Use .join('') to join an array without comma
const createCard = () => {
const pokemonTypes = ['grass', 'fire', 'water'];
return (
`<div>
${pokemonTypes.map(type => `<div>${type}</div>`).join('')}
</div>`
);
}
document.body.insertAdjacentHTML("beforeend", createCard());
CodePudding user response:
The .map() method returns an array. In the template literal `${}` js will convert this array to a string. It does that by default by joining the elements with comma's. You can join the array to a string yourself without a comma:
${pokemonTypes.map(type => `<div>${type}</div>`).join('')}
CodePudding user response:
You can use .join('') for string concrete and the same type used for styling.
const createCard = () => {
const pokemonTypes = ['grass', 'fire', 'water'];
return (
`<div>
${pokemonTypes.map(type => `<div >${type}</div>`).join('')}
</div>`
);
}
document.body.insertAdjacentHTML("beforeend", createCard());
.grass {
color: green
}
.fire {
color: red
}
.water {
color: blue
}
