CSS3 Path (IE9 +)
If you know exactly how deep your last element is, you can redo your calls to :last-child :
li:last-child li:last-child { color: red; }
This pseudo-class selector is not supported in IE prior to version 9, according to http://caniuse.com/#search=last-child . Of course, if you donβt know how deep this list item will be, then this method is not very useful.
JavaScript method
You can also target the last element of the list using JavaScript:
var items = document.getElementById("mylist").getElementsByTagName("li"), _item = items[ items.length - 1 ]; _item.className == "" ? _item.className = "last" : _item.className += " last" ;
This is raw JavaScript that does not require additional frameworks or libraries. If you use a popular framework like jQuery, this could be even simpler:
$("#mylist li:last").addClass("last");
I would not suggest you use jQuery just for something like that. Raw JavaScript will be much faster and much less bloated.
Preprocessor method
Depending on how your navigation menu is configured, you can use the server language to identify the last item in the list and mark it as such. For example, we could do the following using the DOMDocument class in PHP:
$d = new DOMDocument(); $d->loadHTML( $html ); $a = $d->getElementsByTagName("li"); $l = $a->item( $a->length - 1 ); $c = $l->getAttribute("class"); empty( $c ) ? $l->setAttribute("class", "last") : $l->setAttribute("class", "last $c"); echo $d->saveHTML( $l );
This finds the last element of the list in HTML and adds a new βlastβ class to it. The advantage of this is that it does not require a complex and often ineffective CSS3 selector. Furthermore, it does not require the addition of large JavaScript libraries to accomplish trivial things.
Sampson
source share