How to append a childnode to a specific position

前端 未结 3 1832
温柔的废话
温柔的废话 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:08

    For this you have 3 options .insertBefore(), .insertAdjacentElement() or .insertAdjacentHtml()


    .insertBefore()

    var insertedElement = parentElement.insertBefore(newElement, referenceElement);
    

    in your case you could do as on Felix Kling answer

    var insertedElement = parentElement.insertBefore(newElement, parentElement.children[2]);
    

    .insertAdjacentElement()

    referenceElement.insertAdjacentElement (where, newElement);
    

    in your case it would be

    parentElement.children[1].insertAdjacentElement("afterEnd", newElement);
    

    .insertAdjacentHTML()

    referenceElement.insertAdjacentElement (where, newElementHTML);
    

    in your case it would be

    parentElement.children[1].insertAdjacentElement("afterEnd", "<td>newElementHTML</td>");
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-08 04:31

    You can use .insertBefore():

    parentElement.insertBefore(newElement, parentElement.children[2]);
    
    0 讨论(0)
提交回复
热议问题