Distinguish td's using javascript - javascript

I am creating a table, two rows, and two cells in each row in my code. For this purpose, I've got the following code:
var t = document.createElement('table');
document.body.appendChild(t);
for (var x = 0; x <= 1; x++) {
var tr = document.createElement('tr');
t.appendChild(tr);
for (var y = 0; y <= 1; y++) {
var td = document.createElement('td');
tr.appendChild(td);
}
}
Now, I need to create a text node in the first cell and create a a element in the second cell. How would I do that?

It's actually more code to do a "two-step" loop, than to write it out in full:
var t = document.createElement('table'),
trs = [document.createElement('tr'),document.createElement('tr')],
tds = [
[document.createElement('td'),document.createElement('td')],
[document.createElement('td'),document.createElement('td')]
];
trs[0].appendChild(tds[0][0]); trs[0].appendChild(tds[0][1]);
trs[1].appendChild(tds[1][0]); trs[1].appendChild(tds[1][1]);
t.appendChild(trs[0]); t.appendChild(trs[1]);
// now append more stuff here to the tds
document.body.appendChild(t); // do this last - it's better

var t = document.createElement('table');
document.body.appendChild(t);
for (var x = 0; x <= 1; x++) {
var tr = document.createElement('tr');
t.appendChild(tr);
for (var y = 0; y <= 1; y++) {
var td = document.createElement('td');
tr.appendChild(td);
if(y == 0){
alert("here");
var a = document.createElement('A');
td.appendChild(a);
alert("here");
}
else{
var div = document.createElement('div');
td.appendChild(div);
//Create text node
}
}
}
Inside your loop check if y == 0, if it is then you are at your first td therefore you create a link.
If y == 1 you are at the second td therefore you create textnode
Replace div with whatever you want.

inside your second loop just check for if (y == 0) then create text inside the td and if (y == 1) then create an a inside the td.

another way would be to just define the table in text.
eg:
var t = document.createElement('table');
t.innerHTML = "<tr><td>text</td><td><a href='#'>link</a></td></tr><tr><td>text</td><td><a href='#'>link</a></td></tr>";

Related

How can I convert this innerhtml loop to a innertext one because XSS vulnerabilities?

I need to convert this loop to innertext with the dynamically added content how can I do that I looked on the internet but could'nt find anything?
function showMessages(messages) {
jsonMessages.innerHTML = "<tr><th>Naam</th><th>Bericht</th><th>Datum</th></tr>";
messages.sort(function (a, b) {
return a.created_at > b.created_at ? 1 : -1;
});
for (var i = 0; i < messages.length; i++) {
jsonMessages.innerHTML += `<tr><td>${messages[i].user_id}</td><td>${messages[i].content.replace(/</g,"<")}</td><td>${messages[i].created_at}</td></tr>`;
}
console.log(messages);
}
To change your code to prevent xss by using innerText instead of arbitrarily setting innerHTML to some unknown code you will need to create elements themselves first then set their content
For instance
//create a tr element
tr = document.createElement('tr');
//create new cell for above tr
td = tr.insertCell();
td.innerText = messages[i].user_id;
You would do this for the all elements that would have dynamic content. So in your case you could do the following
for (var i = 0; i < messages.length; i++) {
let tr = document.createElement('tr');
let userIdCell = tr.insertCell();
let contentCell = tr.insertCell();
let dateCell = tr.insertCell();
userIdCell.innerText = messages[i].user_id;
contentCell = messages[i].content;
dateCell = messages[i].created_at;
//finally add it to your table
jsonMessages.appendChild(tr);
}
There are other routes that do the same thing, like putting a blank string of your html structure into an element then select the elements and set them:
let tr = document.createElement('tr');
tr.innerHTML = `<tr><td></td><td></td><td></td></tr>`;
//first td child
tr.children[0] = messages[i].user_id;
//second td child
tr.children[1] = messages[i].content;
//third td child
tr.children[2] = messages[i].created_id;
It all just depends on your personal preference. The main point is to just create the elements first then set their innerText property instead of setting the whole html as one.
function showMessages(messages) {
jsonMessages.innerHTML = "<tr><th>Naam</th><th>Bericht</th><th>Datum</th></tr>";
messages.sort(function (a, b) {
return a.created_at > b.created_at ? 1 : -1;
});
for (var i = 0; i < messages.length; i++) {
var mainTr = document.createElement('tr');
var td1 = document.createElement('td').appendChild(document.createTextNode(messages[i].user_id));
var td2 = document.createElement('td').appendChild(document.createTextNode(messages[i].content.replace(/</g,"<")));;
var td3 = document.createElement('td').appendChild(document.createTextNode(messages[i].created_at));
mainTr.appendChild(td1);
mainTr.appendChild(td2);
mainTr.appendChild(td3);
jsonMessages.appendChild(mainTr);
}
console.log(messages);
}

How to dynamically add <a> in a html table?

I have a table generated from an array. I'm looking to add a hyperlink to the entire first column of the <tbody> and only the first column.
I am able to add the <a> after the table is created, but then it doesn't actually contain the url within it, it simply appends to what already exists.
Specifically, how can I add a hyperlink to the first column of the
<tbody>?
Generally, as the table is being made, how can I specify different
things (anchors, classes, styles, etc.) for different columns?
http://jsfiddle.net/nateomardavis/n357gqo9/10/
$(function() {
google.script.run.withSuccessHandler(buildTable)
.table();
});
//TABLE MADE USING for
function buildTable(tableArray) {
var table = document.getElementById('table');
var tableBody = document.createElement('tbody');
var tbodyID = tableBody.setAttribute('id', 'tbody');
for (var i = 0; i < tableArray.length; ++i) {
var column = tableArray[i];
var colA = column[0];
var colB = column[1];
var colC = column[2];
var colD = column[3];
if (colA != "") {
var row = document.createElement('tr');
var getTbody = document.getElementById('tbody');
for (var j = 0; j < column.length; ++j) {
var cell = document.createElement('td');
cell.appendChild(document.createTextNode(column[j]));
row.appendChild(cell);
//NEXT TWO LINES DO NOT WORK
var firstCol = getTbody.rows[i].cells[0];
firstCol.setAttribute('class', 'TEST');
}
}
tableBody.appendChild(row);
}
table.appendChild(tableBody);
document.body.appendChild(table);
/* WORKS AFTER TABLE IS CREATED BUT CAN'T CAPUTRE INTERNAL LINK
var getTbody = document.getElementById('tbody');
for (var i = 0; i < getTbody.rows.length; i++) {
var firstCol = getTbody.rows[i].cells[0]; //first column
//firstCol.style.color = 'red';
//firstCol.setAttribute('class', 'TEST');
var link = document.createElement('a');
firstCol.appendChild(link);
}
*/
}

Create a bookmarklet that can retrieve all max length of text box and then print the id and max length in a table

I want to create a bookmarklet by using javascript, which can retrieve max length of all text box in the page, and then print a table below the page with all id and max length indicated.
Here is my code, however it did not print anything.
javascript: (function() {
var body =document.getElementsByTagName('body')[0];
var tbl = document.createElement('table');
var tbdy = document.createElement('tbody');
var D = document,
i, f, j, e;
for (i = 0; f = D.forms[i]; ++i)
for (j = 0; e = f[j]; ++j)
if (e.type == "text") S(e);
function S(e) {
var l= document.getElementById(e.id);
var x = document.getElementById(e.maxlength);
var tr=document.createElement('tr');
var td1=document.createElement('td');
var td2=document.createElement('td');
td1.appendChild(document.createTextNode(l));
td2.appendChild(document.createTextNode(x));
tr.appendChild(td1);
tr.appendChild(td2);
tbdy.appendChild(tr);
}
tbl.appendChild(tbdy);
body.appendChild(tbl);
})
This can actually be done much simpler than you have it.
Working jsfiddle: https://jsfiddle.net/cecu3daf/
You want to grab all of the inputs and run a loop over them. From this you can dynamically create a table and append it to the end of the document.body
var inputs = document.getElementsByTagName("input"); //get all inputs
var appTable = document.createElement("table"); //create a table
var header = appTable.createTHead(); //create the thead for appending rows
for (var i=0; i<inputs.length; i++) { //run a loop over the input elements
var row = header.insertRow(0); //insert a row to the table
var cell = row.insertCell(0); //insert a cell into the row
cell.innerHTML = inputs[i].maxLength; //input data into the cell
var cell = row.insertCell(0);
cell.innerHTML = inputs[i].id;
}
document.body.appendChild(appTable); //append the table to the document
To make it a bookmark, simply place the javascript: before hand. There is no need to encase it in a function. You can if you'd like to.

Outputting a 3D array as a table

Im making a blackjack game for an assignment and have arrays for leaderboard and cards.
I want to print the leader board like this. CARDS(in individual cells)| TOTAL.
help would be appreciated, thanks
function makeTable(leaderBoard) {
var table = document.createElement('table');
for (var i = 0; i < leaderBoard.length; i++) {
var row = document.createElement('tr');
for (var j = 0; j < leaderBoard[i].length; j++) {
var cell = document.createElement('td');
cell.textContent = leaderBoard[i][j];
row.appendChild(cell);
}
table.appendChild(row);
}
document.getElementById('leaderBoard').innerHTML = table;
}
Maybe the example input isn't in the correct format, but reusing a predefined table and html table functions such as insertRow and insertCell (not necessarily better, but they can be easier on the eye than createElement and append) :
<div id="leaderBoard"><table id=leaderTable></table></div>
function updateleaderboard(leaderBoard) {
var table = document.getElementById('leaderTable');
while(table.rows.length > 0) table.deleteRow(0); //remove prev values, if any
for (var i = 0; i < leaderBoard.length; i++) { //If the function is always used on a winner (no ties), the loop isn't really needed
var row =table.insertRow();
var arrCards = leaderBoard[i++];
var total = row.insertCell();
total.className = 'res';
total.textContent = leaderBoard[i];
arrCards.forEach(function(c,ind){
row.insertCell(ind).textContent = c;
});
}
}
var cards = [['Q','4','5'],19];
updateleaderboard(cards);
Fiddle
function makeTable(leaderBoard) {
var table = document.createElement('table');
var row = document.createElement('tr');
for (var i = 0; i < leaderBoard[0].length; i++) {
var cell = document.createElement('td');
cell.textContent = leaderBoard[0][i];
row.appendChild(cell);
}
var cell = document.createElement('td');
cell.textContent = "Total: " + leaderBoard[1];
row.appendChild(cell);
table.appendChild(row);
document.getElementById('leaderBoard').appendChild(table);
}
var userCards = ["Card 1", "Card 2", "Card 3"];
var userTotal = 10;
makeTable([userCards, userTotal]);
http://jsfiddle.net/25kg3nnq/

MineField with Js

I am trying to create a minefield game with javascript.
When I click on clear ro**w it gives "passed" but sometimes "died" too or clicking on **mined row gives sometimes "passed". It's supposed to give only "passed" with clear and "died" with mined row.
I can't figure out the reason..
Could you see it?
Here is my code so far:
var level = 9;
// create the table
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
tbl.setAttribute('id', 'myTable');
var tblBody = document.createElement("tbody");
//Create 2d table with mined/clear
for (var i = 1; i <= 10; i++) {
var row = document.createElement("tr");
document.write("<br/>");
for (var x = 1; x <= 10; x++) {
var j = Math.floor(Math.random() * 50);
if (j <= 15) {
j = "mined";
} else {
j = "clear";
}
var cell = document.createElement("td");
var cellText = document.createTextNode(j + "");
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "1");
//Check which row is clicked
window.onload = addRowHandlers;
function addRowHandlers() {
var table = document.getElementById("myTable");
var rows = table.getElementsByTagName("td");
for (p = 0; p < rows.length; p++) {
var currentRow = table.rows[p];
var createClickHandler = function (row) {
return function () {
var cell = row.getElementsByTagName("td")[1];
var id = cell.innerHTML;
if (id == "mined") {
alert("Died");
} else {
alert("Passed!");
}
};
}
currentRow.onclick = createClickHandler(currentRow);
}
}
JSFiddle Here:
http://jsfiddle.net/blowsie/ykuyE/
Thanks in advance!
Its' this line, which causes the faulty behaviour: var cell = row.getElementsByTagName("td")[1]; Everytime a click is made, the [1] selects the 2nd cell of a column, no matter which cell was actually clicked.
I modified your fiddle: http://jsfiddle.net/ykuyE/1
The onclick handler is now applied to the individual cell directly, when the table is created.
cell.onclick = function() {
if (this.innerHTML == "mined") {
alert("Died");
} else {
alert("Passed!");
}
}

Categories

Resources