Shishant
Shishant

Reputation: 9294

CSS :last-child selector in javascript?

I am looking to select the last td in each row and using this css selector right now .table td:last-child but it doesnt work in IE so is there any way I can select through javascript (WITHOUT ANY FRAMEWORK) for IE? to apply CSS styles.

Upvotes: 2

Views: 3179

Answers (4)

user113716
user113716

Reputation: 322502

var rows = document.getElementById('tester').rows;

for(var i = 0, len = rows.length; i < len; i++) {
    rows[ i ].lastChild.style.background = 'orange';
}

Example: http://jsfiddle.net/JsyYR/


EDIT: If you'll be running this in all browsers, it may be safer to do this:

var rows = document.getElementById('tester').rows;

for(var i = 0, len = rows.length; i < len; i++) {
    rows[ i ].cells[ rows[ i ].cells.length - 1 ].style.background = 'orange';
}

Example: http://jsfiddle.net/JsyYR/2/

This is because some browsers will insert a text node if there's any space between the last </td> and the closing </tr>. As such, lastChild wouldn't work.

Upvotes: 6

Spudley
Spudley

Reputation: 168715

In Javascript, you can reference .lastChild on any DOM object, but you would have to get the elements first, so without jQuery or similar, it's not as easy as it sounds.

The obvious answer is "Use JQuery". You have specified against this (ie "without any framework"), but it is by far the most obvious solution.

Another solution is Dean Edwards' IE7.js (and related IE8.js and IE9.js) which is a Javascript include that attempts to patch old versions of IE to be more compatible with standard CSS, etc. I believe it fixes :last-child selector. But again, it is a third-party library so you may not want to use it.

You could, of course, just add an additional class to the elements that you want the last child styles to apply to, and then just reference that in your CSS instead of last-child. Not ideal given that last-child is specifically aimed at avoiding you having to do that, but it does give you guaranteed compatibility.

Upvotes: 0

Coin_op
Coin_op

Reputation: 10718

To do this in JavaScript you need something like:

var tableRows = document.getElementById('tableid').childNodes
var tableCells = tableRows[tableRows.length - 1].childNodes;
var lastCell = tableCells[tableCells.length - 1];

This assumes the table is of the format with nothing between those tags. No tbody or such.

Alternatively you could simply use getElementByTagName('td') and get the last element of the returned array. The downside of this is that it won't work for a page with more than one table.

Upvotes: 1

Oli
Oli

Reputation: 239850

Whether you could or not should be moot. Of course you could because Javascript frameworks can do this.

Whether you should spend the time reinventing the wheel when you could just add a small dependency on a JS library, should be the question.

Upvotes: 0

Related Questions