• Item 1
  • Is it possible to replace <li> elements with replaceChild?

    I have a list of items <li>

    :

    <ul id="mylist">
      <li id="item1">Item 1</li>
      <li id="item2">Item 2</li>
      <li id="item3">Item 3</li>
    </ul>
    
          

    Can I swap two elements <li>

    - for example item1 and item2 - using replaceChild

    one of the DOM tree modification methods? Will it work in all browsers?

    +2


    a source to share


    2 answers


    No. replaceChild will remove it from the DOM. Do you want toinsertBefore

    var a = document.getElementById('item1');
    var b = document.getElementById('item2');
    a.parentNode.insertBefore(b, a);
    
          

    Of course, this will only replace them if they are next to each other in the first place.



    You can use replaceChild

    if you want to exchange those that were not next to each other.

    var a = document.getElementById('item1');
    var b = document.getElementById('item3');
    var after_b = b.nextSibling;
    var p = a.parentNode;
    
    p.replaceChild(b,a);
    
    if (after_b) {
        p.replaceChild(a, after_b);
    } else {
       p.appendChild(a);
    } 
    
          

    +6


    a source


    Words, I didn't look very closely at your tags. If jQuery is an option: you can use .insertBefore()

    for this:

    ​$('#item2').insertBefore('#item1');​​​​​​​​​​​​​​​​​​​​
    
          



    Here you can play here , this will cause it not to copy the item, resulting in an exchange.

    +2


    a source







    All Articles