JavaScript Iterate through cell child elements - javascript

I'm attempting to iterate through a html table in javascript and update the id's of the list items within a td tag. I'm currently having trouble on accessing these elements. The tags I need to access are;
<td>
<li id='1'>Curly</li>
<br />
<li id='2'>Larry</li>
<br />
<li id='3'>Moe</li>
</td>
My current JavaScript is below which gets me to the cell. Can anyone advise how to access the Id's of the li?
var table = document.getElementById("tbl_calendar");
for (var i = 0, row; row = table.rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
}
}

You can select all the lis within that cell in the example below using querySelectorAll. Also its not valid HTML to have lis without wrapping them in a ul or ol.
Fiddle: http://jsfiddle.net/AtheistP3ace/ukgfekey/
JS:
var table = document.getElementById("tbl_calendar");
for (var i = 0, row; row = table.rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
var li = col.querySelectorAll('li');
for (var index = 0; index < li.length; index++) {
alert(li[index].id + ': ' + li[index].textContent);
}
}
}
HTML:
<table id="tbl_calendar">
<tr>
<td>
<ul>
<li id='1'>Curly</li>
<br />
<li id='2'>Larry</li>
<br />
<li id='3'>Moe</li>
</ul>
</td>
</tr>
</table>
You also tagged jQuery so in best efforts to be fully explained.
Fiddle: http://jsfiddle.net/AtheistP3ace/ukgfekey/1/
var table = document.getElementById("tbl_calendar");
for (var i = 0, row; row = table.rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
var li = $(col).find('li');
for (var index = 0; index < li.length; index++) {
alert($(li[index]).attr('id') + ': ' + $(li[index]).text());
}
}
}
And as mentioned in comments you don't need all those loops. If you just want all lis from a table you could do this:
Fiddle: http://jsfiddle.net/AtheistP3ace/ukgfekey/2/
var table = document.getElementById("tbl_calendar");
var li, lis = table.querySelectorAll('tr td li');
for (var index = 0; index < lis.length; index++) {
li = lis[index];
alert(li.id + ': ' + li.textContent);
}

you might consider using jQuery something like this
$(document).ready(function(){
$( "td > li" ).each(function() {
$( this ).attr("id","foo" );
});
});

AtheistP3ace already post a good answer but I'm new here and wanted to try to answer myself so here is a fiddle I made, not sure if it's what you want, I used jquery as I see it in your tags : JSFiddle
$("td").each(function() {
$(this).find('li').each(function() {
console.log($(this).attr("id"));
});
});

Related

Add data-title from headline to every td with Javascript (for loop in two dimensional array)

I've got an html table where I want to add the cell content from the headline as data-title to every td for responsive html tables.
The problem is, when I want to set the attribute for the tbody cells, that I got the message:
"array[i] is undefined".
My Javascript Code looks like this:
function myFunction() {
var head = document.querySelector("table > thead");
var body = document.querySelector("table > tbody");
var columncount = body.rows[0].cells.length;
var headItems = head.rows[0].cells;
var headRows = head.rows;
var headCells = [];
var array = []
if (headItems.length == columncount) {
for (var i = 0; i < headRows.length; i++) {
var columns = [];
headCells = headRows[i].cells;
for (var m = 0; m < headCells.length; m++) {
columns[m] = headCells[m].innerHTML;
}
array[i] = columns;
}
}
var bodyRows = body.rows;
for (j = 0; j < bodyRows.length; j++) {
var bodyCells = bodyRows[j].cells;
for (k = 0; k < bodyCells.length; k++) {
bodyCells[k].setAttribute("data-title", array[i][m]); // NOTE array[i][m] here
}
}
}
If you use jQuery in your project this could help:
// Add data-title to every <td>
$( "table" ).each( function( index, tableID ) {
$( tableID ).find( "thead tr th" ).each( function( index ) {
index += 1;
$( tableID ).find( "tbody tr td:nth-child(" + index + ")" ).attr( "data-title", $(this).text() );
});
});
Works only for tables which have <thead> and <tbody> tags inside.
First of all, when you choose a variable, don't use a javascript keyword name, for example, instead of using array, use _array or arr or other variables.
I think you need to add a content to this array. Try to add something to your array, because if you do array[i], array is empty and don't have i index.
Try this:
_array.push(some_value);
Then, you can do this _array[0] for instance.

Append image to td element with no id or value

I have an array of image elements, I use a function to randomize the array and I would like to append them back to the HTML table in their randomized order. However I am trying to avoid giving each td element it's own id because there are quite a few...I am wondering if it's possible to append the image to the td element with it not having a id.
The HTML table has about 12 rows that would be like this:
<table class="piecetray">
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
etc...
JS
function randomizePieces(myArray) {
for (var i = myArray.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = myArray[i];
myArray[i] = myArray[j];
myArray[j] = temp;
}
return array;
}
Assuming the table is already built and you want to iterate through each td and update it's background with just plain js.
// lets start by getting the `table` element
var tbl = document.getElementsByClassName("piecetray");
// lets get all the child rows `tr` of the `table`
var trs = tbl[0].childNodes[1].getElementsByTagName("tr");
var trlen = trs.length;
//just a test image
var host = "http://upload.wikimedia.org";
var img = host + "/wikipedia/commons/thumb/2/25/Red.svg/200px-Red.svg.png";
// iterate over the rows `tr`
for (var i = 0; i < trlen; i++) {
//get the `td`s for this row
var tds = trs[i].getElementsByTagName("td");
var tdlen = tds.length;
//iterate over the cells `td`
for (var n = 0; n < tdlen; n++) {
//set `backgroundImage`
tds[n].style.backgroundImage = "url(\"" + img + "\")";
}
}
See the JSFiddle, hopefully this at least points you in the right direction.
I believe this is the basic idea of what you are looking for.
$('#table').html(''); //clear the table
for(var x = 0, len = array.length; x < len; x++){ //fill the table
$('#table').append('<tr>');
$('#table').append('<td>' + array[x] + '</td>'); //can also add img tag here if you get the SRC for the image
$('#table').append('</tr>');
}
<table id="table"></table>
Would it be something like that
$(document).ready(function(e) {
$.each($('.piecetray tr td'), function(index, value){
var img = $('<img />').attr('src', '').attr('title', index);
$(value).append(img);
});
});
DEMO

Traverse the HTML document

I am using the following code to traverse one forum
var formWithTable = document.getElementsByTagName("table")[0];
var table = formWithTable.getElementsByTagName("tbody")[0];
var rows = table.getElementsByTagName("tr");
for(i = 0; i < rows.length; i++)
{
var cols = rows[i].getElementsByTagName("td");
for (j = 0; j < cols.length; j++)
{
...
}
}
The HTML document is as follows:
<div>
<table class="inventory sortable" id="listContainer_datatable" summary="Properties of various threads" title="Properties of various threads">
<thead>
<tr>
...
<tbody id="listContainer_databody">
<tr id="listContainer_row:0" class="">
<td class="smallCell" valign="top">
<input type="checkbox" name="formCBs" value="2161433" id="listContainer_formCBs2161433" title="Add a new message." />
<label for="listContainer_formCBs2161433" id="listContainer_formCBs2161433Label" class="hideoff">
</label>
</td>
...
</table>
</div>
However, I do not know that why document.getElementsByTagName("table")[0] returns "undefined".
Any help is very appreciated.
What you really should be using is jQuery. Then you can just do this:
$("table")[0]
to select the first table of the document. Simple as that.
In other news, if that is your document, it isn't valid HTML, so Javascript DOM isn't guaranteed to work.
Your script is fine, the only problem might be the script is added before the table is added to the dom, that could be the cause of the problem.
The solution is to move the script to window.onload
window.onload = function(){
var formWithTable = document.getElementsByTagName("table")[0];
var table = formWithTable.getElementsByTagName("tbody")[0];
var rows = table.getElementsByTagName("tr");
for(i = 0; i < rows.length; i++) {
var cols = rows[i].getElementsByTagName("td");
for (j = 0; j < cols.length; j++) {
console.log(cols[j].innerHTML)
}
}
}
Demo: Fiddle

Separate rows and columns while creating 2d dynamic table

I can't separate row and column td's as I create a 2d table with jquery..
How do I create 10 rows 10 columns 2d table:
what I have done so far:
$(document).ready(function () {
for (var i = 1; i <= 10; i++) {
$('.box').append('<td/>' + '</p>');
for (var j = 1; j <= 10; j++); {
$('.box').append('<td/>');
}
}
});
http://jsfiddle.net/VS37n/
thnx in advance!
You want a table that has 10 columns and 10 rows.
var rows = 10;
var cols = 10;
In an HTML table structure, rows come first in the hierarchy, so, create those first:
$(document).ready(function() {
var rows = 10;
var cols = 10;
var box = $('.box');
for (var r = 0; r < rows; r++) {
var tr = $('<tr>');
//Here we will append the columns to the row before appending it to the box.
box.append(tr);
}
});
The above code only makes 10 rows for us. Now we need to add 10 columns to each row:
$(document).ready(function() {
var rows = 10;
var cols = 10;
var box = $('.box');
for (var r = 0; r < rows; r++) {
var tr = $('<tr>');
for (var c = 0; c < cols; c++) {
tr.append($('<td><p></p></td>')); //Create the table cell, with a p element as in your example, and append it to the row.
}
box.append(tr);
}
});
See this FIDDLE
UPDATE
I just noticed that the jQuery selector from your post selects the <div> element with class .box. You want to add these rows and columns, however, to a <table> element, which doesn't exist. I'd suggest you add a <table> element into your HTML, or, add it with Javascript before adding the rows.
If you can add a <table> element inside of your .box div, then you would just change the following line:
var box = $('.box');
to:
var box = $('.box table:first');
If you can't change the HTML for some reason, then you can dynamically create the table before the rows and columns:
var box = $('<table>').appendTo('.box');
Is this what you're trying to do?
$(document).ready(function () {
var tdHtml = "":
var trHtml = "";
var tableHtml = "";
for(var i=1;i<=10;i++)
{
tdHtml += "<td></td>";
}
for(var j=1;j<=10;j++);
{
trHtml += ("<tr>" + tdHtml + "</tr>");
}
tableHtml = ("<table>" + trHtml + "</table>");
$('.box').innerHtml(tableHtml);
});
You had a ; after your for loop :
for (var j = 1; j <= 10; j++); {
$('.box').append('<td/>');
}
Furthermore, you are not adding <tr> elements.
See the updated fiddle

Combine HTML Table Rows with Javascript

Is there an easy way to combine rows in an HTML table where the first column is the same? I basically have a table set up like:
<table>
<tr><td>test</td><td>12345</td><td>12345</td><tr>
<tr><td>test</td><td>12345</td><td>12345</td><tr>
<tr><td>test2</td><td>12345</td><td>12345</td><tr>
<tr><td>test</td><td>12345</td><td>12345</td><tr>
<tr><td>test2</td><td>12345</td><td>12345</td><tr>
</table>
and I want it to generate:
<table>
<tr><td>test</td><td>37035</td><td>37035</td><tr>
<tr><td>test2</td><td>24690</td><td>24690</td><tr>
</table>
using jQuery:
var map = {};
$('table tr').each(function(){
var $tr = $(this),
cells = $tr.find('td'),
mapTxt = cells.eq(0).text();
if(!map[mapTxt]){
map[mapTxt] = cells;
} else {
for(var i=1, l=cells.length; i<l; i++){
var cell = map[mapTxt].eq(i);
cell.text(parseInt(cell.text()) + parseInt(cells[i].text()));
}
$tr.remove();
}
});
this is a "dumb" script -- no error handling for cases like different number of cells, fields being non-numeric, etc. Add those if necessary.
Also, depending on how it's generated, it's better to do this server-side.
Here's a plain JavaScript version.
window.onload = function() {
var table = document.getElementById('mytable');
var tr = table.getElementsByTagName('tr');
var combined = Array();
for (i = 0; i < tr.length; i++) {
var td = tr[i].getElementsByTagName('td');
var key = td[0].innerText;
if (!combined[key]) {//if not initialised
combined[key] = Array();
for (j = 0; j < td.length - 1; j++) combined[key][j] = 0;
}
for (j = 0; j < td.length - 1; j++)
combined[key][j] += parseInt(td[j + 1].innerText);
}
while (table.hasChildNodes()) table.removeChild(table.lastChild);
var tbody = document.createElement('tbody');//needed for IE
table.appendChild(tbody);
for (var i in combined) {
tr = document.createElement('tr');
tbody.appendChild(tr);
td = document.createElement('td');
td.innerText = i;
tr.appendChild(td);
for (j = 0; j < combined[i].length; j++) {
td = document.createElement('td');
td.innerText = combined[i][j];
tr.appendChild(td);
}
}
}
This will work on tables with any number of rows and any number of cells. I suppose you want to make the sum for every column, that's what this script does.
And as cwolves mentioned, it is more logical to do this serverside. Users that have JS disabled will see the not so clean uncombined table.

Categories