HEYHEY February 2016

jQuery push giving a comma

So, I am pushing objects using push in js.

I am appending this object into html:

var top = [];

for (var i = 0; i < 1; i++) {                                                   
    var file= something[i];
    top.push(file);     
};

jQuery('.place').append(top);

I am noticing that there is a comma in between the file variable:

<div class="place"> 
   <div class="name">something</div>
   ,
   <div class="name">else</div> 
</div>

I am guessing this comma is there as the result of push event.

How do I get rid of it?

Any suggestions?

Thanks

Answers


Adam February 2016

You are passing an array of strings to jQuery's append method. Simply join it first:

jQuery('.place').append(top.join(''));

When you call toString() on an array (which is what jQuery is doing here when you try to append an array of strings) it casts each array element to a string and puts a comma between them:

[1,2,3].toString(); //"1,2,3"
[{a:"b"},2,3].toString(); //"[object Object],2,3"


Gavriel February 2016

First of all it looks there's a problem using top as variable name, so I changed it to top1.

THEORY: According to http://api.jquery.com/append/ you can pass an array of DOM elements, or String(s) (or other things, but they're not related to the question). You seem to pass an array of strings, that is not an array of DOM elements, so it's being stringified, and the stringification of an array has commas between the elements. I'm pretty sure you also have a "[" before them and a "]" after them.

PRACTICE: Well, I don't seem to reproduce your problem (at least in Chrome, FF, Safari):

var top1 = [];

for (var i = 0; i < 2; i++) {                                                   
    var file = "<div>something[i]</div>";
    top1.push(file);     
}

$('#place').append(top1);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="place"> 
</div>

Post Status

Asked in February 2016
Viewed 1,791 times
Voted 10
Answered 2 times

Search




Leave an answer