Best way to implement .lastChild using Prototype or jQuery

We are currently using prototype and jQuery as our js frameworks. Right now, jQuery is set to $ j () to prevent prototype conflicts.

In the past, we used many prototypes of Element.down (), Element.next (), and Element.previous () to traverse the DOM. However, I need an easy way to get the last child. I know that I can iterate over an array using Element.childElements (), but I would like something inline that reads cleanly and can be pipelined.

Just thought I'd ask before I reinvent the wheel again. Here is a snippet of code that has lastChild in it that needs to be replaced:

_find : function(rows, address) { var obj = null; for (var i=0; i < rows.length && obj == null; i++) { if (rows[i].down().className == 'b') obj = this._find(rows[i].lastChild.down().down().childElements(), address); else if (rows[i].lastChild.getAttribute('tabAddress') == address) return rows[i].lastChild; } return obj; } 
+6
javascript jquery prototypejs
source share
5 answers

Guys, note that the selector functions return arrays of elements (not individual elements), so you must adddress the element in the result array by index: [0].

Prototype code

 //if you only have the id of the parent var lastChild = $$("#parent :last-child")[0]; //or //if you have the actual DOM element var lastChild = $(element).select(":last-child")[0]; 

JQuery code

 //if you only have the id of the parent var lastChild = $("#parent :last-child")[0]; //or //if you have the actual DOM element var lastChild = $(":last-child", element)[0]; 

Code in plain vanilla javascript

 var element = document.getElementById("parent"); var lastChild = element.childNodes[element.childNodes.length - 1]; 

Also note that they can return null if the parent does not have child nodes.

+21
source share

Try this, it always worked for me in jQuery

 var lastChild = $("#parent :last-child"); 

http://docs.jquery.com/Selectors/lastChild

+1
source share

Using Prototype, you can use the $$ utility function, which supports most of the CSS3 syntax:

 var lastChild = $$(".b:last-child")[0]; 
+1
source share

If someone finds this while searching the web to answer their question, with Prototype you can do:

 Element.childElements().last(); 
0
source share

For anyone else who still uses Prototype, you can add your own element methods:

Element.addMethods({ ... });

I added these two among others:

 first: function(element) { element = $(element); return element.childElements()[0]; }, last: function(element) { element = $(element); var i = element.childElements().size() - 1; return element.childElements()[i]; } var first = $('foo').first(); var last = $('foo').last(); 

The Element.first() method is kind of redundant, I use it for cleaner code while chaining.

Make sure you reutrn element chain.

0
source share

All Articles