我有一个元素E,我向它添加了一些元素。突然间,我发现下一个要追加的元素应该是e的第一个子元素,有什么诀窍,怎么做呢?方法unshift不起作用,因为E是一个对象,而不是数组。

很长的路要走,遍历E的孩子,并移动他们的键++,但我相信有一个更好的方法。


当前回答

我创建这个原型是为了将元素前置到父元素。

Node.prototype.prependChild = function (child: Node) {
    this.insertBefore(child, this.firstChild);
    return this;
};

其他回答

除非我误解了:

$("e").prepend("<yourelem>Text</yourelem>");

Or

$("<yourelem>Text</yourelem>").prependTo("e");

虽然从你的描述听起来是有附加条件的,所以

if (SomeCondition){
    $("e").prepend("<yourelem>Text</yourelem>");
}
else{
    $("e").append("<yourelem>Text</yourelem>");
}

你可以实现它直接在你所有的窗口html元素。 像这样:

HTMLElement.prototype.appendFirst = function(childNode) {
    if (this.firstChild) {
        this.insertBefore(childNode, this.firstChild);
    }
    else {
        this.appendChild(childNode);
    }
};

我认为您正在寻找jQuery中的.prepend函数。示例代码:

$("#E").prepend("<p>Code goes here, yo!</p>");
var eElement; // some E DOM instance
var newFirstElement; //element which should be first in E

eElement.insertBefore(newFirstElement, eElement.firstChild);

我创建这个原型是为了将元素前置到父元素。

Node.prototype.prependChild = function (child: Node) {
    this.insertBefore(child, this.firstChild);
    return this;
};