0

I'm trying to get the innerText values from all the 'a' tags in my document with this loop.

var x = document.getElementById("toplist-artists");
                    var y = x.getElementsByTagName("a");
                    var nodeListLength = y.length;

                    for (i=0;i<nodeListLength;i++) {
                        var artists = x.innerText;
                    }

                    console.log(artists);

This works and now I want to separate these values with a comma or space. When I add + ',' to x.innertext a comma only shows at the end of the 'list'. Like this:

Tom Odell
Elbow
Aloe Blacc
Michael Prins
, 

Can someone please tell me how to get it to show like this

Tom Odell,
Elbow,
Aloe Blacc,
Michael Prins,
user3182261
  • 271
  • 2
  • 10
  • 21
  • `innerText` is not supported by all browsers. I recommend using libraries like jQuery. For more details, read [this post](http://stackoverflow.com/a/1359822/3215948). – Racil Hilan Mar 27 '14 at 13:38

2 Answers2

1

First, fix your loop: as it stands, it's meaningless, as you don't change the variable based on the loop counter. It has to be y[i], not x.innerText; otherwise why do it inside the loop?

Second, use the loop to collect all the texts in an array. Then it'll be trivial to get a string you need - just use join to concatenate all the values into a single one, using commas and EOL as delimiters:

var artists = [];
for (var i=0; i < nodeListLength; i++) {
  artists.push( y[i].textContent ); // `textContent` supported by all but IE8-
}
console.log(artists.join(',\n'));
raina77ow
  • 103,633
  • 15
  • 192
  • 229
0

Try this

var artists = "";
for (i=0;i<nodeListLength;i++) {
    artists += x.innerText+", ";
}
mulla.azzi
  • 2,676
  • 4
  • 18
  • 25