I have table, with data, and i need for td:eq(4) change class, and box for baghround.
I have this code:
$('tr').each(function () {
var rowCol = $(this);
rowCol.find('td:eq(4)').each(function () {
var rowValue = parseFloat($(this).text());
console.log(rowValue === 0)
if (rowValue > 1) {
$('.defects').addClass('def').removeClass('defects');
} else {
$('.def').addClass('defects').removeClass('def');
}
});
});
.defects {
background: #e74c3c;
color: #fff;
padding: 3px;
border-radius: 6px;
}
And if at this td i have value more then 1, i add bg red box.
But nox, something went wrong.
Without seeing your html, I can only guess about how it looks based on your code, but try this:
$('tr').each(function() {
var rowCol = $(this);
rowCol.find('td:eq(4)').each(function() {
var mytd = $(this);
var rowValue = parseFloat($(this).text());
console.log(rowValue === 0)
if (rowValue > 1) {
mytd.addClass('def').removeClass('defects');
} else {
mytd.addClass('defects').removeClass('def');
}
});
});
first of, I'm assigning your td:eq(4) to a variable var mytd = $(this);.
then I'm replacing $('.defects') with mytd
Code
$('tr').each(function() {
var rowCol = $(this);
rowCol.find('td:eq(4)').each(function() {
var mytd = $(this);
var rowValue = parseFloat($(this).text());
console.log(rowValue === 0)
if (rowValue > 1) {
mytd.addClass('def').removeClass('defects');
} else {
mytd.addClass('defects').removeClass('def');
}
});
});
.defects {
background: #e74c3c;
color: #fff;
padding: 3px;
border-radius: 6px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>0</td>
<td>6</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
</table>
You can run the demo above and see the result.
Related
I have a table that I use jQuery to color even and odd rows mainly because I want the user to chose which color he wants from few selections in form
But when I setup bgcolor of a table in css, the jQuery script won't work.
Below is the code to change the colors (jsfiddle https://jsfiddle.net/sh7cgaz4/)
It stops working when adding to the css, eg:
table,th,td {
background-color: red;
}
here is the fiddle when it stops working: https://jsfiddle.net/8g7wn0ov/
$(function() {
var colors = [{
display: "jasny żółty",
value: "ffffcc"
}, {
display: "jasny niebieski",
value: "ccffff"
}, {
display: "jasny zielony",
value: "ccffcc"
}, {
display: "szary",
value: "cccccc"
}, {
display: "biały",
value: "ffffff"
}];
var options = ['<option value="">wybierz kolor</option>'];
for (var i = 0; i < colors.length; i++) {
options.push('<option value="');
options.push(colors[i].value);
options.push('">');
options.push(colors[i].display);
options.push('</option>');
}
$('#koloryparzyste').html(options.join('')).change(function() {
var val = $(this).val();
if(val){
$('.parzyste').css('backgroundColor', '#' + val);
}
});
var options = ['<option value="">wybierz kolor</option>'];
for (var i = 0; i < colors.length; i++) {
options.push('<option value="');
options.push(colors[i].value);
options.push('">');
options.push(colors[i].display);
options.push('</option>');
}
$('#kolorynieparzyste').html(options.join('')).change(function() {
var val = $(this).val();
if (val) {
$('.nieparzyste').css('backgroundColor', '#' + val);
}
});
Your issue is that you are setting the css background colour on the table,th,td but in your javascript, you're only updating the tr (.nieparzyste / .parzyste which is a class on the tr).
As a td sits inside or "on top" of a tr the td colour overrides the tr colour.
You can fix this by setting the "default" (in the css) colour only on the tr, or by changing the jquery to also update the td.
Snippet using tr colour:
$(function() {
var colors = [{
display: "jasny żółty",
value: "ffffcc"
}, {
display: "jasny niebieski",
value: "ccffff"
}, {
display: "jasny zielony",
value: "ccffcc"
}, {
display: "szary",
value: "cccccc"
}, {
display: "biały",
value: "ffffff"
}];
var options = ['<option value="">wybierz kolor</option>'];
for (var i = 0; i < colors.length; i++) {
options.push('<option value="');
options.push(colors[i].value);
options.push('">');
options.push(colors[i].display);
options.push('</option>');
}
$('#koloryparzyste').html(options.join('')).change(function() {
var val = $(this).val();
if (val) {
$('.parzyste').css('backgroundColor', '#' + val);
}
});
var options = ['<option value="">wybierz kolor</option>'];
for (var i = 0; i < colors.length; i++) {
options.push('<option value="');
options.push(colors[i].value);
options.push('">');
options.push(colors[i].display);
options.push('</option>');
}
$('#kolorynieparzyste').html(options.join('')).change(function() {
var val = $(this).val();
if (val) {
$('.nieparzyste').css('backgroundColor', '#' + val);
}
});
});
table,
th,
td {
border: 1px solid black;
border-collapse: collapse;
text-align: center;
}
table tr {
background-color: pink;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="prawy">
<table id="kolorwa">
<tr class="parzyste">
<th>Lp.</th>
<th>Imię</th>
<th>Nazwisko</th>
<th>Stanowisko</th>
<th>Data zatrudnienia</th>
<th>Ilość dni urlopowych</th>
</tr>
<tr class="nieparzyste">
<td>1</td>
<td>Barbar</td>
<td>Sznuk</td>
<td>Dział Hr</td>
<td>11.06.2002</td>
<td>1</td>
</tr>
<tr class="parzyste">
<td>2</td>
<td>Tomasz</td>
<td>Kopyra</td>
<td>Pracwnik Produkcji</td>
<td>11.06.2005</td>
<td>11</td>
</tr>
<tr class="nieparzyste">
<td>3</td>
<td>Tomasz</td>
<td>Bukowski</td>
<td>Pracwnik Produkcji</td>
<td>02.01.2007</td>
<td>10</td>
</tr>
<tr class="parzyste">
<td>4 </td>
<td>Janusz</td>
<td>Tracz</td>
<td>Kierownik</td>
<td>21.06.2007</td>
<td>3</td>
</tr>
<tr class="nieparzyste">
<td>5</td>
<td>Grzegorz</td>
<td>Kowalski</td>
<td>Dyrektor</td>
<td>29.09.1999</td>
<td>15</td>
</tr>
</table>
<form name="koloryparzyste">Tu zmienisz kolory parzyste<br>
<select id="koloryparzyste"></select>
</form>
<form name="kolorynieparzyste">Tu zmienisz kolory nieparzyste<br>
<select id="kolorynieparzyste"></select>
</form>
</div>
you are looking for background-color instead of backgroundColor
$('.nieparzyste').css('background-color', '#' + val);
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 3 years ago.
Is there any way to user mousedown event on dynamically added elements
$(function() {
var isMouseDown = false,
isHighlighted;
//$('#our_table').on('mousedown', 'tr', function (event) {
$("#myTable tr").mousedown(function() {
isMouseDown = true;
$(this).toggleClass("highlighted");
isHighlighted = $(this).hasClass("highlighted");
return false; // prevent text selection
}).mouseover(function() {
if (isMouseDown) {
$(this).toggleClass("highlighted", isHighlighted);
}
}).bind("selectstart", function() {
return false;
})
$(document).mouseup(function() {
isMouseDown = false;
});
});
function addRow() {
var arrTables = document.getElementById('myTable');
var oRows = arrTables.rows;
var numRows = oRows.length;
var newRow = document.getElementById('myTable').insertRow(numRows);
var cell1 = newRow.insertCell(0);
var cell2 = newRow.insertCell(1);
var cell3 = newRow.insertCell(2);
cell1.innerHTML = numRows;
cell2.innerHTML = numRows;
cell3.innerHTML = numRows;
}
table td {
width: 100px;
height: 50px;
text-align: center;
vertical-align: middle;
background-color: #ccc;
border: 1px solid #fff;
}
table tr.highlighted td {
background-color: #999;
}
body {
user-select: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table cellpadding="0" cellspacing="0" id="myTable">
<tr>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>2</td>
<td>2</td>
</tr>
</table>
<button onclick="addRow()">Add Row</button>
You have to set the event delegation to body element and then match the event.target to the element you want to trigger your action.
You can check this start, updated your fiddle only for the mousedown method: http://jsfiddle.net/Len7csa0/
I need help with fixing my movement code. I am not so javascript friendly. I am just using the old fashion table technique and javascript. I cannot use any jquery or other sources. Here is the code:
<html>
<head>
<style>
table, td {
border: solid black;
text-align: center;
background-color: #DCDCDC;
}
td {
width: 20px;
}
</style>
<script>
var bposr =3; // blank position : row
var bposc=3; // blank position : column
function keypress() {
var ieKey = event.keyCode;
if (ieKey == 40 && bposr!=0){ // for moving down
temp= document.getElementById("myTable").rows[bposr-1].cells[bposc].innerHTML;
document.getElementById("myTable").rows[bposr-1].cells[bposc].innerHTML=document.getElementById("myTable").rows[bposr].cells[bposc].innerHTML;
document.getElementById("myTable").rows[bposr].cells[bposc].innerHTML=temp;
document.getElementById("myTable").rows[bposr].cells[bposc].style.backgroundColor='#DCDCDC';
document.getElementById("myTable").rows[bposr-1].cells[bposc].style.backgroundColor='#ffffff';
bposr--;
}
else if (ieKey == 37 && bposc!=1){ // for moving right
temp= document.getElementById("myTable").rows[bposr].cells[bposc+1].innerHTML;
document.getElementById("myTable").rows[bposr].cells[bposc+1].innerHTML=document.getElementById("myTable").rows[bposr].cells[bposc].innerHTML;
document.getElementById("myTable").rows[bposr].cells[bposc].innerHTML=temp;
document.getElementById("myTable").rows[bposr].cells[bposc].style.backgroundColor='#DCDCDC';
document.getElementById("myTable").rows[bposr].cells[bposc+1].style.backgroundColor='#ffffff';
bposc++;
}
else if (ieKey == 39 && bposc!=1){ // for moving left
temp= document.getElementById("myTable").rows[bposr].cells[bposc+1].innerHTML;
document.getElementById("myTable").rows[bposr].cells[bposc+1].innerHTML=document.getElementById("myTable").rows[bposr].cells[bposc].innerHTML;
document.getElementById("myTable").rows[bposr].cells[bposc].innerHTML=temp;
document.getElementById("myTable").rows[bposr].cells[bposc].style.backgroundColor='#DCDCDC';
document.getElementById("myTable").rows[bposr].cells[bposc+1].style.backgroundColor='#ffffff';
bposc++;
}
else if (ieKey == 38 && bposr!=0){ // for moving down
temp= document.getElementById("myTable").rows[bposr-1].cells[bposc].innerHTML;
document.getElementById("myTable").rows[bposr-1].cells[bposc].innerHTML=document.getElementById("myTable").rows[bposr].cells[bposc].innerHTML;
document.getElementById("myTable").rows[bposr].cells[bposc].innerHTML=temp;
document.getElementById("myTable").rows[bposr].cells[bposc].style.backgroundColor='#DCDCDC';
document.getElementById("myTable").rows[bposr-1].cells[bposc].style.backgroundColor='#ffffff';
bposr--;
}
}
function start(){
document.onkeydown = keypress;
}
</script>
</head>
<body onLoad="start()">
<center>
<table id="myTable">
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
</tr>
<tr>
<td>9</td>
<td>10</td>
<td>11</td>
<td>12</td>
</tr>
<tr>
<td>13</td>
<td>14</td>
<td>15</td>
<td style="background-color:white;"></td>
</tr>
</table>
<br>
</body>
</html>
You have some logic errors in the movement conditions, besides that your code works just fine.
var Table = document.getElementById("myTable");
var bposr =3; // blank position : row
var bposc=3; // blank position : column
function keypress(ieKey) {
var ieKey = event.keyCode;
var Table = document.getElementById("myTable");
console.log(Table);
console.log(ieKey);
if (ieKey == 40 && bposr != 0){ // for moving down
console.log(bposr);
temp = Table.rows[bposr - 1].cells[bposc].innerHTML;
Table.rows[bposr - 1].cells[bposc].innerHTML = Table.rows[bposr].cells[bposc].innerHTML;
Table.rows[bposr].cells[bposc].innerHTML = temp;
Table.rows[bposr].cells[bposc].style.backgroundColor = '#DCDCDC';
Table.rows[bposr - 1].cells[bposc].style.backgroundColor = '#ffffff';
bposr--;
} else if (ieKey == 39 && bposc != 0){ // for moving right
console.log(bposc);
temp = Table.rows[bposr].cells[bposc - 1].innerHTML;
Table.rows[bposr].cells[bposc - 1].innerHTML = Table.rows[bposr].cells[bposc].innerHTML;
Table.rows[bposr].cells[bposc].innerHTML = temp;
Table.rows[bposr].cells[bposc].style.backgroundColor = '#DCDCDC';
Table.rows[bposr].cells[bposc - 1].style.backgroundColor = '#ffffff';
bposc--;
} else if (ieKey == 37 && bposc != 3){ // for moving left
console.log(bposc);
temp = Table.rows[bposr].cells[bposc + 1].innerHTML;
Table.rows[bposr].cells[bposc + 1].innerHTML = Table.rows[bposr].cells[bposc].innerHTML;
Table.rows[bposr].cells[bposc].innerHTML = temp;
Table.rows[bposr].cells[bposc].style.backgroundColor = '#DCDCDC';
Table.rows[bposr].cells[bposc + 1].style.backgroundColor = '#ffffff';
bposc++;
} else if (ieKey == 38 && bposr != 3){ // for moving up
console.log(bposr);
temp = Table.rows[bposr + 1].cells[bposc].innerHTML;
Table.rows[bposr + 1].cells[bposc].innerHTML = Table.rows[bposr].cells[bposc].innerHTML;
Table.rows[bposr].cells[bposc].innerHTML = temp;
Table.rows[bposr].cells[bposc].style.backgroundColor = '#DCDCDC';
Table.rows[bposr + 1].cells[bposc].style.backgroundColor = '#ffffff';
bposr++;
}
}
function start(){
document.onkeydown = keypress;
}
table, td {
border: solid black;
text-align: center;
background-color: #DCDCDC;
}
td {
width: 20px;
}
<center>
<table id="myTable">
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
</tr>
<tr>
<td>9</td>
<td>10</td>
<td>11</td>
<td>12</td>
</tr>
<tr>
<td>13</td>
<td>14</td>
<td>15</td>
<td style="background-color:white;"></td>
</tr>
</table>
<br>
</center>
Thanks for the randomize code. I will see if it is beatable before I finish it.
I have this table:
<table border="1">
<tr>
<td></td>
<td>Banana</td>
<td>Orange</td>
<td>Plum</td>
</tr>
<tr>
<td>Banana</td>
<td>1:1</td>
<td>1:2</td>
<td>1:3</td>
</tr>
<tr>
<td>Orange</td>
<td>2:1</td>
<td>1:1</td>
<td>1,5:1</td>
</tr>
<tr>
<td>Plum</td>
<td>1:3</td>
<td>2:1</td>
<td>1:1</td>
</tr>
and CSS:
td {
height:60px;
width:60px;
text-align:center;
}
td:hover{
background-color:red;
}
What I want to do, is when I for example point my mouse on 1:3 table cell, it should highlight together with Banana and Plum cells.
Any easy way to do it?
Here's fiddle:
http://jsfiddle.net/CZEJT/
If you dont mind a bit of Javascript in there to ensure compatibility, take a look at this JSFiddle
HTML:
<table>
<tr>
<th></th><th>50kg</th><th>55kg</th><th>60kg</th><th>65kg</th><th>70kg</th>
</tr>
<tr>
<th>160cm</th><td>20</td><td>21</td><td>23</td><td>25</td><td>27</td>
</tr>
<tr>
<th>165cm</th><td>18</td><td>20</td><td>22</td><td>24</td><td>26</td>
</tr>
<tr>
<th>170cm</th><td>17</td><td>19</td><td>21</td><td>23</td><td>25</td>
</tr>
<tr>
<th>175cm</th><td>16</td><td>18</td><td>20</td><td>22</td><td>24</td>
</tr>
</table>
CSS:
table {
border-spacing: 0;
border-collapse: collapse;
overflow: hidden;
z-index: 1;
}
td, th, .ff-fix {
cursor: pointer;
padding: 10px;
position: relative;
}
td:hover::after,
.ff-fix:hover::after {
background-color: #ffa;
content: '\00a0';
height: 10000px;
left: 0;
position: absolute;
top: -5000px;
width: 100%;
z-index: -1;
}
tr:hover{
background-color: #ffa;
}
}
JS:
function firefoxFix() {
if ( /firefox/.test( window.navigator.userAgent.toLowerCase() ) ) {
var tds = document.getElementsByTagName( 'td' );
for( var index = 0; index < tds.length; index++ ) {
tds[index].innerHTML = '<div class="ff-fix">' + tds[index].innerHTML + '</div>';
};
var style = '<style>'
+ 'td { padding: 0 !important; }'
+ 'td:hover::before, td:hover::after { background-color: transparent !important; }'
+ '</style>';
document.head.insertAdjacentHTML( 'beforeEnd', style );
};
};
firefoxFix();
below is an example from one of my sites (css):
/*when hover over shape 5 dim shape 5*/
#shape5{
opacity:1.0;
filter:alpha(opacity=100);}
#shape5:hover{
opacity:0.4;
filter:alpha(opacity=40);}
/*When hoverover text5 dim shape 5!*/
#text5:hover + #shape5{opacity:0.4;
filter:alpha(opacity=40);}
Hope that helps!!
Oh Also view: How to affect other elements when a div is hovered
would you like something like this?
unfortunately it would be necessary some javascript
HTML
<table border="1">
<tr>
<td></td>
<td id='1'>Banana</td>
<td id='2'>Orange</td>
<td id='3'>Plum</td>
</tr>
<tr>
<td>Banana</td>
<td class='o1'>1:1</td>
<td class='o2'>1:2</td>
<td class='o3'>1:3</td>
</tr>
<tr>
<td>Orange</td>
<td class='o1'>2:1</td>
<td class='o2'>1:1</td>
<td class='o3'>1,5:1</td>
</tr>
<tr>
<td>Plum</td>
<td class='o1'>1:3</td>
<td class='o2'>2:1</td>
<td class='o3'>1:1</td>
</tr>
</table>
JAVASCRIPT
var cells1 = $('.o1');
cells1.on('mouseover', function(){
$($(this).parent().children()[0]).css({background: '#ddd'})
$('#1').css({background: '#ddd'})
})
cells1.on('mouseout', function(){
$($(this).parent().children()[0]).css({background: 'none'})
$('#1').css({background: 'none'})
})
var cells2 = $('.o2');
cells2.on('mouseover', function(){
$($(this).parent().children()[0]).css({background: '#ddd'})
$('#2').css({background: '#ddd'})
})
cells2.on('mouseout', function(){
$($(this).parent().children()[0]).css({background: 'none'})
$('#2').css({background: 'none'})
})
var cells3 = $('.o3');
cells3.on('mouseover', function(){
$($(this).parent().children()[0]).css({background: '#ddd'})
$('#3').css({background: '#ddd'})
})
cells3.on('mouseout', function(){
$($(this).parent().children()[0]).css({background: 'none'})
$('#3').css({background: 'none'})
})
CSS
td {
height:60px;
width:60px;
text-align:center;
}
td:hover{
background-color:red;
}
Try this:
Fiddle
Without changing your html structure or adding any third party library:
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function () {
var tds = document.getElementsByTagName('td');
for (var i = 0; i < tds.length; i++) {
var elem = document.getElementsByTagName('td')[i];
elem.addEventListener('mouseover', function () {
var text = this.innerHTML;
for (var j = 0; j < tds.length; j++) {
var elem2 = document.getElementsByTagName('td')[j];
if (elem2.innerHTML == text) {
elem2.style.background = 'red';
}
}
}, false);
elem.addEventListener('mouseout', function () {
for (var j = 0; j < tds.length; j++) {
var elem2 = document.getElementsByTagName('td')[j];
var text = this.innerHTML;
if (elem2.innerHTML == text) {
elem2.style.background = 'none';
}
}
}, false);
}
}, false);
</script>
I apologise that my answer is only in pseudo code, however I would approach this problem by using javascript (most possibly Jquery). I hope this makes sense...
<table id="tbl"> - so I would give the table an ID
<td onHover="changeHeaderColummns(this)"></td> - then on each of the columns have a jsMethod that fires.
<script>
changeHeaderColumsn(col)
{
var colIndex = col.Index; //get the current column index
var row = GetHeaderRow(); // get the header row
highLightColumn(row, colIndex); //change the colour of the cell
//with the same index in the header
row = getCurrentRow(col.RowIndex); //now get the current row
highlightColumn(row, 0); //change the colour of the cell
//with the index of 0
}
getHeaderRow()
{
return getRow(0);
}
getRow(rowIndex)
{
var table = document.getElementByID("tbl);
return table.rows[rowIndex];
}
highlightColumn(row, colIndex)
{
row[colIndex].style.backgroundcolor = "red";
}
for highlight columns you must use js like this jsfiddler. It's work with jQuery ;)
With code
Using jquery
fiddle: http://jsfiddle.net/itsmikem/CZEJT/12/
Option 1: highlights the cell and just the named fruit cells
$("td").on({
"mouseenter":function(){
$(this).closest("tr").find("td:first-child").css("background","#f99");
var col = $(this).index();
$(this).closest("table").find("tr:first-child").find(String("td:nth-child(" + (col + 1) + ")")).css("background","#f99");
$(this).css("background","#f00");
},
"mouseleave":function(){
$(this).closest("table").find("td,tr").css("background","none");
}
});
Option 2: highlights entire rows and columns that intersect the hovered cell
$("td").on({
"mouseenter": function () {
$(this).closest("tr").css("background", "#f99");
var col = $(this).index();
var myTable = $(this).closest("table");
var rows = $(myTable).find("tr");
$(rows).each(function (ind, elem) {
var sel = String("td:nth-child(" + (col + 1) + ")");
$(this).find(sel).css("background", "#f99");
});
$(this).css("background", "#f00");
},
"mouseleave": function () {
$(this).closest("table").find("td,tr").css("background", "none");
}
});
I have the following table being rendered in my browser. It's generated from the server side.
<table id="tblQuestions" class="tblQuestionsContainer" border="0">
<tr>
<td id="1" class="tdQuestion">Are u an indian citizen ?</td>
</tr><tr>
<td><table id="answer-1" border="0">
<tr>
<td><input id="answer-1_0" type="radio" name="answer-1" value="1" /><label for="answer-1_0">Yes</label></td><td><input id="answer-1_1" type="radio" name="answer-1" value="0" /><label for="answer-1_1">No</label></td>
</tr>
</table></td>
</tr><tr>
<td id="2" class="tdQuestion">Do you have a passport ?</td>
</tr><tr>
<td><table id="answer-2" border="0">
<tr>
<td><input id="answer-2_0" type="radio" name="answer-2" value="1" /><label for="answer-2_0">Yes</label></td><td><input id="answer-2_1" type="radio" name="answer-2" value="0" /><label for="answer-2_1">No</label></td>
</tr>
</table></td>
</tr>
</table>
Now I am using the following code in my JavaScript to validate the radio button's checked state.
var tblQuestionBoard=document.getElementById("tblQuestions");
tblAnswer = tblQuestionBoard.rows[1].childNodes[0].childNodes[0]
Now tblAnswer should be an object having the Table with id "answer-1"
In IE, I am getting it. But in Mozilla and rest of the browsers I am getting it as undefined.
How to solve this?
It's because you're using childNodes and whitespaces in the DOM are considered to be text nodes by Firefox et. al but not IE
See this answer for an explanation
My suggestions
1.Set up some wrapper functions that ignore any nodeType other than 1 (ELEMENT_NODE) to do DOM traversing. Something like
function child(elem, index) {
// if index is not supplied, default is 1
// you might be more comfortable making this 0-based
// in which case change i initial assignment value to 0 too
index = index || 1;
// get first child element node of elem
elem = (elem.firstChild && elem.firstChild.nodeType != 1) ?
next(elem.firstChild) :
elem.firstChild;
// use the index to move to nth-child element node
for(var i=1; i < index;i++) {
(function() {
return elem = next(elem);
})();
}
return elem;
}
function next(elem) {
do {
elem = elem.nextSibling;
} while (elem && elem.nodeType != 1);
return elem;
}
and use like so - Working Demo - (Code at the bottom of the answer for reference)
<table id="myTable">
<thead>
...
</thead>
<tbody>
...
</tbody>
</table>
<script type="text/javascript">
child(document.getElementById('myTable'), 2); // will get the tbody
</script>
2.Use getElementbyId(), getElementsByTagName() or getElementsByName() instead of relying on position in the DOM
3.Use a JavaScript library that abstracts away browser differences (jQuery comes highly recommended)
The Demo Code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script type="text/javascript">
window.onload = function() {
document.getElementById('getCellContents').onclick = getCellContents;
}
function child(elem, index) {
index = index || 1;
elem = (elem.firstChild && elem.firstChild.nodeType != 1) ?
next(elem.firstChild) :
elem.firstChild;
for(var i=1; i < index;i++) {
(function() {
return elem = next(elem);
})();
}
return elem;
}
function next(elem) {
do {
elem = elem.nextSibling;
} while (elem && elem.nodeType != 1);
return elem;
}
function getCellContents() {
var row = parseInt(document.getElementById('row').value, 10);
var column = parseInt(document.getElementById('column').value, 10);
var result;
var color;
var table = document.getElementById('table');
var cells = table.getElementsByTagName('td');
for (var i= 0; i < cells.length; i++) {
(function() {
cells[i].bgColor = '#ffffff';
})();
}
if (row && column) {
var tbody = child(table , 2);
var selectedRow = (row <= tbody.getElementsByTagName("tr").length)? child(tbody, row): null;
var selectedCell = (selectedRow && column <= selectedRow.getElementsByTagName("td").length)? child(selectedRow, column): null;
if (selectedRow && selectedCell) {
selectedCell.bgColor = '#00ff00';
result = selectedCell.innerHTML;
color = '#b7b7b7';
}
else {
result = 'Cell does not exist';
color = '#ff0000';
}
}
else {
result = 'You must provide numeric arguments for Row and Column Number';
color = '#ff0000';
}
var results = document.getElementById('results');
results.innerHTML = result;
results.style.color = color;
}
</script>
<title>DOM Traversal</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<style type="text/css">
body {
font-family: Verdana, Helvetica, Arial;
font-size: 0.8em;
}
h2 {
text-align:center;
}
table {
border: 1px solid #000;
border-collapse: collapse;
}
th, td {
border: 1px solid #000;
padding: 2px;
}
fieldset {
border: 0;
}
label {
display: block;
width: 120px;
text-align: right;
float: left;
padding-right: 10px;
margin: 5px 0;
}
input {
margin: 5px 0;
}
input.text {
padding: 0 0 0 3px;
width: 172px;
}
input.button {
margin: 15px 0 0 130px;
}
span {
font-weight: bold;
color: #b7b7b7;
}
</style>
</head>
<body>
<h2>Example to demonstrate use of JavaScript DOM traversing wrapper functions</h2>
<div style="margin: 0 auto; width: 600px;">
<fieldset>
<label for="row">Row Number:</label><input id="row" class="text" type="text" /><br/>
<label for="column">Column Number:</label><input id="column" class="text" type="text" /><br/>
<input id="getCellContents" type="button" class="button" value="Get Cell Contents" />
</fieldset>
<p>Results: <span id="results"></span></p>
<table id="table">
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
<th>Column 4</th>
<th>Column 5</th>
</tr>
</thead>
<tbody>
<tr>
<td>Banana</td>
<td>Apple</td>
<td>Orange</td>
<td>Pineapple</td>
<td>Cranberry</td>
</tr>
<tr>
<td>Monkey</td>
<td>Giraffe</td>
<td>Elephant</td>
<td>Tiger</td>
<td>Snake</td>
</tr>
<tr>
<td>C#</td>
<td>Java</td>
<td>Python</td>
<td>Ruby</td>
<td>Haskell</td>
</tr>
<tr>
<td>France</td>
<td>Spain</td>
<td>Italy</td>
<td>Germany</td>
<td>Netherlands</td>
</tr>
</tbody>
</table>
<p style="font-weight:bold;">The Code:
<pre><code>
<script type="text/javascript">
window.onload = function() {
document.getElementById('getCellContents').onclick = getCellContents;
}
function child(elem, index) {
index = index || 1;
elem = (elem.firstChild && elem.firstChild.nodeType != 1) ?
next(elem.firstChild) :
elem.firstChild;
for(var i=1; i < index;i++) {
(function() {
if(elem)
return elem = next(elem);
})();
}
return elem;
}
function next(elem) {
do {
elem = elem.nextSibling;
} while (elem && elem.nodeType != 1);
return elem;
}
function getCellContents() {
var row = parseInt(document.getElementById('row').value, 10);
var column = parseInt(document.getElementById('column').value, 10);
var result;
var color;
var table = document.getElementById('table');
var cells = table.getElementsByTagName('td');
for (var i= 0; i < cells.length; i++) {
(function() {
cells[i].bgColor = '#ffffff';
})();
}
if (row && column) {
var tbody = child(table , 2);
var selectedRow = (row <= tbody.getElementsByTagName("tr").length)?
child(tbody, row): null;
var selectedCell = (selectedRow && column <= selectedRow.getElementsByTagName("td").length)?
child(selectedRow, column): null;
if (selectedRow && selectedCell) {
selectedCell.bgColor = '#00ff00';
result = selectedCell.innerHTML;
color = '#b7b7b7';
}
else {
result = 'Cell does not exist';
color = '#ff0000';
}
}
else {
result = 'You must provide numeric arguments for Row and Column Number';
color = '#ff0000';
}
var results = document.getElementById('results');
results.innerHTML = result;
results.style.color = color;
}
</script>
</code>
</pre>
</p>
</div>
</body>
</html>