Çetin
Çetin

Reputation: 117

innerHTML injects unwanted characters between items

I'm trying to inject array of items to html with innerHTML.

let itemsToInject = [`<li><img src='icon1.png' alt=''></li>`,`<li><img src='icon2.png' alt=''></li>`];
content.innerHTML = itemsToInject.map(item => item);

It works perfectly and injects items. However, there is a problem in DOM. It automatically inserts unwanted characters (",") between list items.

Looks like that:

<li>...</li>
","
<li>...</li>

I've tried to remove them by regex, but it failed.

Upvotes: 1

Views: 44

Answers (2)

rafalou38
rafalou38

Reputation: 602

You have to use .join("") to join all element of the array together:

elements = ["<p>hello</p>", "<p>bye</p>"]

document.querySelector("#without").innerHTML = elements
document.querySelector("#with").innerHTML    = elements.join("")
<div id="without"></div>
<br/><br/>
<div id="with"></div>

Upvotes: 1

Endothermic_Dragon
Endothermic_Dragon

Reputation: 1187

Try something like this:

content = document.body
let itemsToInject = [`<li>IMG 1<img src='icon1.png' alt=''></li>`, `<li>IMG 2<img src='icon2.png' alt=''></li>`];
itemsToInject.forEach(item => content.innerHTML += item);

Or this:

content = document.body
let itemsToInject = [`<li>IMG 1<img src='icon1.png' alt=''></li>`, `<li>IMG 2<img src='icon2.png' alt=''></li>`];
content.innerHTML = itemsToInject.join('')

The situation is being caused because you are setting the innerHTML to a javascript list, so the browser is forced to convert it to a string - and that's exactly what it does.

To avoid it, simply don't pass an array or list into innerHTML!

Upvotes: 2

Related Questions