简体   繁体   中英

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.

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.

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM