using javascript's .insertBefore to insert item as last child

前端 未结 6 986
梦谈多话
梦谈多话 2020-12-18 01:15

I so miss jQuery. I\'m working on a project where I need to get my hands dirty with good \'ol plain Javascript again.

I have this scenario:

parent
           


        
6条回答
  •  轮回少年
    2020-12-18 01:41

    Modern Solution

    If you want to position based on child, simply use before or after

    child1.before(newNode)   // [newNode, child1, child2]
    // or
    child1.after(newNode)    // [child1, newNode, child2]
    

    If you want to position based on parent, use prepend or append

    parent.prepend(newNode)  // [newNode, child1, child2]
    // or
    parent.append(newNode)   // [child1, child2, newNode]
    

    Advanced usage

    1. You can pass multiple values (or use spread operator ...).
    2. Any string value will be added as a text element.

    Examples:

    child1.after(newNode, "foo")     // [child1, newNode, "foo", child2]
    
    const list = ["bar", newNode]
    parent.prepend(...list, "fizz")  // ["bar", newNode, "fizz", child1, child2]
    

    Mozilla Docs

    before - after

    prepend - append

    Can I Use - 93% Aug 2020

提交回复
热议问题