问题
I need to find the Last td of every row in a HTML table, and remove a css from that td. Can I do it without using Jquery. How?
回答1:
You can use css3 last-child
property for this. Write like this:
tr td:last-child{
color:red;
}
But it's not work in IE8 & below.
回答2:
Use CSS
td:last-child: {
//your style here
}
Docs on CSS3 selectors here
or using traverse the DOM using JavaScript :
var mytable = document.getElementById('tableid');
var myrows = mytable.getElementsByTagName("tr");
var lastrow = myrows[myrows.length -1];
var mycells = lastrow.getElementsByTagName("td");
var lastcell = mycells[mycells.length -1];
// set CSS property here
lastcell.style.color = "red";
lastcell
is your last td
Working example using JavaScript
回答3:
Have you tried using CSS3 selectors? E.g
tr td:last-child
{
YOUR CODE HERE
}
You could also look at using classes to show which td's are the last. But of course this isnt dynamic.
I believe there is also a normal javascript answer but im not very good at that :P
http://www.w3.org/TR/selectors/
http://www.quirksmode.org/css/firstchild.html
回答4:
Assuming that you are not looking for css type solution
rows=document.getElementsByTagName('tr')
for (var i=0; i<rows.length; i++){
columns=rows[i].getElementsByTagName('td');
mytd = columns[columns.length-1];
classname = mytd.className;
arr = classname.split(' ');
mytd.className = arr.filter(function(e){return e!=CLASSTOREMOVE}).join(' ');
}
回答5:
For a pure JavaScript solution:
function removeCssClass(tableId, cssClass) {
var trs = null;
var tr = null;
var tds = null;
var td = null;
var classes = [];
var i = 0;
trs = document.getElementById(tableId).getElementsByTagName('tr');
tds = trs[trs.length - 1].getElementsByTagName('td');
td = tds[tds.length - 1];
classes = td.className.split(' ');
for (i = 0; i < classes.length; i += 1) {
if (classes[i] === cssClass) {
classes.pop(i);
}
}
td.className = classes.join(' ');
return false;
}
Working fiddle.
回答6:
What are you trying to do with the last TD? If you are wanting to have a border in-between each td why don't you use border-left and then you can use first-child to remove it. There might be a better approach that is more compatible with browsers.
来源:https://stackoverflow.com/questions/9718449/find-last-td-without-using-jquery