【问题标题】:How to set DOM element as the first child?如何将 DOM 元素设置为第一个子元素?
【发布时间】:2011-01-01 17:12:09
【问题描述】:

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

很长的路要遍历 E 的孩子并移动他们的 key++,但我确信有一个更漂亮的方法。

【问题讨论】:

  • 你们速度很快!对不起,我想我被误解了。元素 e |- child-el_1 |- child-el_2 |- child-el_3 然后是 child-el_4 ...,它需要适合作为第一个孩子。 prepend 会将 child-el_4 放在 [b]e[/b] 之前,我是错了还是累了?

标签: javascript jquery arrays dom elements


【解决方案1】:
var eElement; // some E DOM instance
var newFirstElement; //element which should be first in E

eElement.insertBefore(newFirstElement, eElement.firstChild);

【讨论】:

  • 你我的朋友,你自己刚买了一只熊!有用的额外发现。 docs.jquery.com/Manipulation/insertBefore
  • 有关信息,如果父项中没有元素,则无论如何都会添加子项。
  • 如果 firstChild 是文本节点抛出异常。但 jquery 不会预先添加。
  • @Sergey,也适用于我的文本节点,在 Firefox 和 Chromium 上进行了测试。你用的是什么浏览器?你确定问题不在你这边吗?你愿意准备一个重现问题的 sn-p/jsfiddle 吗?
  • list.outerHTML = entry.outerHTML + list.outerHTML;希望对某人有所帮助。
【解决方案2】:

2018版-prepend

parent.prepend(newChild)  // [newChild, child1, child2]

这是现代 JS!它比以前的选项更具可读性。它目前在 Chrome、FF 和 Opera 中可用。

添加到末尾的等价物是append,替换旧的appendChild

parent.append(newChild)  // [child1, child2, newChild]

高级用法

  1. 您可以传递多个值(或使用扩展运算符...)。
  2. 任何字符串值都将作为文本元素添加。

示例:

parent.prepend(newChild, "foo")   // [newChild, "foo", child1, child2]

const list = ["bar", newChild]
parent.append(...list, "fizz")    // [child1, child2, "bar", newChild, "fizz"]

相关的 DOM 方法

  1. Read More - child.beforechild.after
  2. Read More - child.replaceWith

Mozilla Documentation

Can I Use

【讨论】:

  • 很好的解决方案,谢谢!令我恼火的是,他们决定在末尾添加一个孩子是.appendChild(),但将它添加到开头是.prepend(),而不是坚持惯例并称之为.prependChild()
  • append() 也存在,工作方式与prepend() 相同,但在最后
  • 当我看到这些关于实现prepend 的问题时,我也感到困惑,而我发现它已经是那样了。 :( 好吧,过去不存在。
  • @Marquizzo,为什么不使用append?对于 backcompat,显然不能直接删除 appendChild
【解决方案3】:

2017版

你可以使用

targetElement.insertAdjacentElement('afterbegin', newFirstElement)

来自MDN

insertAdjacentElement() 方法将给定元素节点插入到相对于调用它的元素的给定位置。

位置
一个 DOMString 表示相对于元素的位置;必须是以下字符串之一:
beforebegin:在元素本身之前。
afterbegin:就在元素内部,在它的第一个子元素之前。
beforeend:就在元素内部,之后它的最后一个子元素。
afterend: 在元素本身之后。

元素
要插入到树中的元素。

insertAdjacent 的家族中也有兄弟方法:

element.insertAdjacentHTML('afterbegin','htmlText') 用于直接注入 html 字符串,如 innerHTML 但不会覆盖所有内容,因此您可以跳过 document.createElement 的压迫过程,甚至可以通过字符串操作过程构建整个组件

element.insertAdjacentText 用于将净化字符串注入元素。没有了encode/decode

【讨论】:

  • 很好的建议,但为什么“回到 2017”,即使在 ie8 上也是标准方法
  • 谢谢。再次感谢您的洞察力。标题是为了帮助人们快速区分这是新的答案
  • 如果 element = document.importNode(documentfragment, true) 会怎样?
  • 返回element typeof document-fragment 没有insertAdjacent...()。在我们有更好的答案之前,您最好的猜测是将 fragment 附加到 div 。进行 dom 操作,然后使用 Range.selectNodeContents()Range.extractContents() 取回片段
  • 其中'element'是你要添加的元素,'element'是你要添加的元素;)
【解决方案4】:

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

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

【讨论】:

  • prepend 是原版 JS 的等价物,不需要原型。它将在 ES7 中成为标准,如果可能,您应该在您的应用程序中使用它
  • @Gibolt - DOM API 方法与 ECMAScript 版本无关。
  • yorg - 仅供参考,可以将null 作为insertBefore 中的参考元素传递,不需要上面的分支。
【解决方案5】:

将接受的答案重构为函数:

function prependChild(parentEle, newFirstChildEle) {
    parentEle.insertBefore(newFirstChildEle, parentEle.firstChild)
}

【讨论】:

  • +1 用于使用父子关系。接受的答案缺乏这一点。我需要知道eElement 是什么才有意义。为此,我需要阅读这个问题。大多数时候,我只是检查标题并直接进入答案,而忽略了问题的详细信息。
【解决方案6】:

除非我有误解:

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

或者

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

虽然从你的描述中听起来像是附加了一些条件,所以

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

【讨论】:

  • $ 版本+1!我正在编写一个 jQuery 扩展函数,因此出于性能原因,我将尽可能使用本机版本,但这是完美的!
  • 不,他在寻找 JavaScript,而不是 jquery。
【解决方案7】:

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

$("#E").prepend("<p>Code goes here, yo!</p>");

【讨论】:

  • 你们速度很快!对不起,我想我被误解了。元素 e |- child-el_1 |- child-el_2 |- child-el_3 然后是 child-el_4 ...,它需要适合作为第一个孩子。 prepend 会将 child-el_4 放在 [b]e[/b] 之前,我是错了还是累了?
【解决方案8】:

我创建了这个原型来将元素添加到父元素。

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

【讨论】:

    【解决方案9】:
    var newItem = document.createElement("LI");       // Create a <li> node
    var textnode = document.createTextNode("Water");  // Create a text node
    newItem.appendChild(textnode);                    // Append the text to <li>
    
    var list = document.getElementById("myList");    // Get the <ul> element to insert a new node
    list.insertBefore(newItem, list.childNodes[0]);  // Insert <li> before the first child of <ul>
    

    https://www.w3schools.com/jsref/met_node_insertbefore.asp

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-17
      • 1970-01-01
      • 1970-01-01
      • 2018-01-29
      • 1970-01-01
      • 1970-01-01
      • 2021-12-01
      • 2018-11-27
      相关资源
      最近更新 更多