00Gheist00
00Gheist00

Reputation: 145

Random commas in my HTML

I have commas between my HTML buttons and i don't know where they come from. The div in which i create the buttons is empty before the buttons are being created.

In my JavaScript, i don't have any commas that could be put between the buttons as you can see below.

Here is a picture:

enter image description here

I create the buttons with JavaScript like so:

    var f = "'";
    contents[0]='<button class="btn" onclick="check('+ f + randomChar0 + f +');">' + randomChar0 + '</Button>';
    contents[1]='<button class="btn" onclick="check('+ f + randomChar1 + f +');">' + randomChar1 + '</Button>';
    contents[2]='<button class="btn" onclick="check('+ f + randomChar2 + f +');">' + randomChar2 + '</Button>';

    ranNum0 = randomize(2);
    document.getElementById("response").innerHTML = contents;

My HTML looks like this before i insert the buttons:

<div id="response" class="center-children">
</div>

And like this after i insert the buttons:

<div id="response" class="center-children">
    <button class="btn" onclick="check('B');">B</button>,
    <button class="btn" onclick="check('S');">S</button>,
    <button class="btn" onclick="check('E');">E</button>
</div>

If i check in the Browser, it looks like this:

enter image description here

I checked my whole JavaScript, even tried to delete all the CSS and HTML but the commas remain there...

Does anyone have a clue what might cause this?

Upvotes: 8

Views: 2284

Answers (2)

JLRishe
JLRishe

Reputation: 101690

The problem is that you are assigning the string value of your array to .innerHTML and the string value of an array has commas between the elements.

In order to combine the values in your array, use .join():

 document.getElementById("response").innerHTML = contents.join('');

Or better yet, don't use string manipulation to create DOM elements.

Upvotes: 13

Raphael Serota
Raphael Serota

Reputation: 2197

You're setting innerHTML to be an array, but it's supposed to be a string. Implicitly, .toString() is being called on your array, which leaves commas. Try it out, [1,2,3].toString() evaluates to "1,2,3".

Upvotes: 3

Related Questions