使用Prototype或jQuery实现.lastChild的最佳方法

tac*_*aco 6 javascript jquery prototypejs

目前我们正在使用prototype和jQuery作为我们的js框架.现在,jQuery设置为$ j()以防止原型冲突.

在过去,我们使用了很多原型的Element.down(),Element.next()和Element.previous()来遍历DOM.但是,我需要一种简单的方法来检索最后一个子元素.我知道我可以通过使用Element.childElements()来遍历一个数组,但我想要一些内联,它可以干净地读取并且可以流水线化.

我想在重新发明轮子之前我会问.这里有一段代码,其中包含需要替换的lastChild:

_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;
    }
Run Code Online (Sandbox Code Playgroud)

Leo*_*Leo 21

伙计们,请注意,选择器函数返回元素数组(不是单个元素),因此必须通过索引在结果数组中添加元素:[0].

原型代码

//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]; 
Run Code Online (Sandbox Code Playgroud)

Jquery中的代码

//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]; 
Run Code Online (Sandbox Code Playgroud)

简单的香草javascript中的代码

var element = document.getElementById("parent");
var lastChild = element.childNodes[element.childNodes.length - 1];
Run Code Online (Sandbox Code Playgroud)

另请注意,如果父元素没有子节点,则这些元素可以返回null.