How to append a childnode to a specific position

前端 未结 3 1841
温柔的废话
温柔的废话 2020-12-08 03:53

How can I append a childNode to a specific position in javascript?

I want to add a childNode to the 3rd position in a div. There are other nodes behind it that need

3条回答
  •  情书的邮戳
    2020-12-08 04:19

    To insert a child node at a specific index

    Simplified,

    Element.prototype.insertChildAtIndex = function(child, index) {
      if (!index) index = 0
      if (index >= this.children.length) {
        this.appendChild(child)
      } else {
        this.insertBefore(child, this.children[index])
      }
    }
    

    Then,

    var child = document.createElement('div')
    var parent = document.body
    parent.insertChildAtIndex(child, 2)
    

    Tada!

    Be aware of when extending natives could be troublesome

提交回复
热议问题