I’m new to js and looking for someone to help me with it. I have created javascript table with the following code:
JavaScript
x
20
20
1
data = { players: [
2
{ name: 'aphra', score: 10, ping: 20 }
3
] };
4
5
const addRow = (el, data) => {
6
if (data.players.length) {
7
data.players.forEach((ply) => {
8
9
const row = document.createElement("tr");
10
row.innerHTML = `
11
<td>${ply.name}</td>
12
<td>${ply.score}</td>
13
<td>${ply.ping == '0' ? 'BOT' : ply.ping}</td>
14
`;
15
el.appendChild(row);
16
});
17
}
18
};
19
const table = document.getElementById('id')
20
addRow(table, data);
JavaScript
1
1
1
<table id="id"></table>
I’m trying to apply given below code function with the <td>${ply.name}</td>
in my table js
js code function I want to apply https://jsfiddle.net/tdwcqze0/
Advertisement
Answer
Use:
<td>${generate_colored_span(ply.name).innerHTML}</td>
Instead of
<td>${ply.name}</td>
JavaScript
1
58
58
1
function generate_colored_span(text, className = null) {
2
let cont = document.createElement('span')
3
let txtary = []
4
let curtxt = ''
5
let curcol = '7'
6
7
for (let i = 0; i < text.length; i++) {
8
if (text[i] == '^') {
9
if (curtxt) {
10
curobj = {}
11
curobj.txt = curtxt
12
curobj.col = curcol
13
txtary.push(curobj)
14
}
15
curtxt = ''
16
i += 1
17
curcol = text[i]
18
} else {
19
curtxt += text[i]
20
}
21
}
22
curobj = {}
23
curobj.txt = curtxt
24
curobj.col = curcol
25
txtary.push(curobj)
26
27
txtary.forEach((txt) => {
28
let txtsp = document.createElement('span')
29
txtsp.className = 'tracker_col' + txt.col
30
txtsp.appendChild(document.createTextNode(txt.txt))
31
cont.appendChild(txtsp)
32
})
33
if (className) cont.className = className
34
return cont
35
}
36
37
const addRow = (el, data) => {
38
if (data.players.length) {
39
data.players.forEach((ply) => {
40
41
const row = document.createElement("tr");
42
row.innerHTML = `
43
<td>${generate_colored_span(ply.name).innerHTML}</td>
44
<td>${ply.score}</td>
45
<td>${ply.ping == '0' ? 'BOT' : ply.ping}</td>
46
`;
47
el.appendChild(row);
48
});
49
}
50
};
51
const table = document.getElementById('id')
52
addRow(table, {
53
players: [{
54
name: 'foo',
55
score: 1,
56
ping: 0
57
}]
58
});
JavaScript
1
3
1
.tracker_col7 {
2
background: red;
3
}
JavaScript
1
1
1
<table id="id"></table>