Applying class tags to individual JavaScript Array entries after sorting

Viewed 16

I am trying to apply the same css class to each indivdual entry in the created array, but instead I am getting it apllied once to the whole array.

My Code is as follows..

    function sortballhistory() {
        var str = document.getElementById("ballhistory").innerText;
    var temp = new Array();
    // This will return an array with strings "1", "2", etc.
    temp = str.split(",");
    temp.sort(function (a, b) {  return a - b;  });
    temp = 'temp.slice(1);
    document.getElementById('ballhistorysortedarr').innerHTML = temp;

}; 

ballhistory innerText contains shuffled numbers 1-90 like (2, 5, 7, 76, etc) these change each page load.

I have tried 1)

temp = '<span class="smallball">' + temp.slice(1) + '</span>';
document.getElementById('ballhistorysortedarr').innerHTML = temp;

and also tried 2)

  document.getElementById('ballhistorysortedarr').innerHTML = '<span class="smallball">' + temp; + '</span>';

and also 3)

 document.getElementById('ballhistorysortedarr').innerHTML += '<span class="smallball">' + temp; + '</span>';

But non of them give the desired result of styling each entry seperatly.

1 Answers

You need to iterate through each element in the temp array and return the element wrapped inside the span. That's how you can provide the class to the span, Please check the code below, and let me know if this is what you were trying to achieve.

var btn = document.getElementById("btn");

btn.addEventListener('click', function() {
  sortballhistory();
})

function sortballhistory() {
        var str = document.getElementById("ballhistory").innerText;
    var temp = new Array();
    // This will return an array with strings "1", "2", etc.
    temp = str.split(",");
    temp.sort(function (a, b) {  return a - b;  });
    var result = '';
    for(var i=0; i<temp.length; i++) {
      result+="<span class='item'>" + temp[i] + "</span>"
    }
    document.getElementById('ballhistorysortedarr').innerHTML = result;

}; 
.item {
  color: red;
}
<div id="ballhistory">2, 3, 5,4, 6, 2, 5, 1, 8, 4</div>
<button id='btn'>Click</button>

<div id='ballhistorysortedarr'></div>

Related