I'm new to js and looking for someone to help me with it. I have created javascript table with the following code:
data = { players: [
{ name: 'aphra', score: 10, ping: 20 }
] };
const addRow = (el, data) => {
if (data.players.length) {
data.players.forEach((ply) => {
const row = document.createElement("tr");
row.innerHTML = `
<td>${ply.name}</td>
<td>${ply.score}</td>
<td>${ply.ping == '0' ? 'BOT' : ply.ping}</td>
`;
el.appendChild(row);
});
}
};
const table = document.getElementById('id')
addRow(table, data);
<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/
CodePudding user response:
Use:
<td>${generate_colored_span(ply.name).innerHTML}</td>
Instead of
<td>${ply.name}</td>
function generate_colored_span(text, className = null) {
let cont = document.createElement('span')
let txtary = []
let curtxt = ''
let curcol = '7'
for (let i = 0; i < text.length; i ) {
if (text[i] == '^') {
if (curtxt) {
curobj = {}
curobj.txt = curtxt
curobj.col = curcol
txtary.push(curobj)
}
curtxt = ''
i = 1
curcol = text[i]
} else {
curtxt = text[i]
}
}
curobj = {}
curobj.txt = curtxt
curobj.col = curcol
txtary.push(curobj)
txtary.forEach((txt) => {
let txtsp = document.createElement('span')
txtsp.className = 'tracker_col' txt.col
txtsp.appendChild(document.createTextNode(txt.txt))
cont.appendChild(txtsp)
})
if (className) cont.className = className
return cont
}
const addRow = (el, data) => {
if (data.players.length) {
data.players.forEach((ply) => {
const row = document.createElement("tr");
row.innerHTML = `
<td>${generate_colored_span(ply.name).innerHTML}</td>
<td>${ply.score}</td>
<td>${ply.ping == '0' ? 'BOT' : ply.ping}</td>
`;
el.appendChild(row);
});
}
};
const table = document.getElementById('id')
addRow(table, {
players: [{
name: 'foo',
score: 1,
ping: 0
}]
});
.tracker_col7 {
background: red;
}
<table id="id"></table>