Skip to main content

JavaScript moving element in the DOM



Let's say I have three <div> elements on a page. How can I swap positions of the first and third <div> ? jQuery is fine.





Source: Tips4all

Comments

  1. Trivial with jQuery

    $('#div1').insertAfter('#div3');
    $('#div3').insertBefore('#div2');


    If you want to do it repeatedly, you'll need to use different selectors since the divs will retain their ids as they are moved around.

    $(function() {
    setInterval( function() {
    $('div:first').insertAfter($('div').eq(2));
    $('div').eq(1).insertBefore('div:first');
    }, 3000 );
    });

    ReplyDelete
  2. There's no need to use a library for such a trivial task:

    var divs = document.getElementsByTagName("div"); // order: first, second, third
    divs[2].parentNode.insertBefore(divs[2], divs[0]); // order: third, first, second
    divs[2].parentNode.insertBefore(divs[2], divs[1]); // order: third, second, third


    This takes account of the fact that getElementsByTagName returns a live NodeList that is automatically updated to reflect the order of the elements in the DOM as they are manipulated.

    You could also use:

    var divs = document.getElementsByTagName("div"); // order: first, second, third
    divs[0].parentNode.appendChild(divs[0]); // order: second, third, first
    divs[1].parentNode.insertBefore(divs[0], divs[1]); // order: third, second, third


    and there are various other possible permutations, if you feel like experimenting:

    divs[0].parentNode.appendChild(divs[0].parentNode.replaceChild(divs[2], divs[0]));


    for example :-)

    ReplyDelete
  3. jQuery.fn.swap = function(b){
    b = jQuery(b)[0];
    var a = this[0];
    var t = a.parentNode.insertBefore(document.createTextNode(''), a);
    b.parentNode.insertBefore(a, b);
    t.parentNode.insertBefore(b, t);
    t.parentNode.removeChild(t);
    return this;
    };


    and use it like this:

    $('#div1').swap('#div2');


    if you don't want to use jQuery you could easily adapt the function.

    ReplyDelete
  4. var swap = function () {
    var divs = document.getElementsByTagName('div');
    var div1 = divs[0];
    var div2 = divs[1];
    var div3 = divs[2];

    div3.parentNode.insertBefore(div1, div3);
    div1.parentNode.insertBefore(div3, div2);
    };


    This function may seem strange, but it heavily relies on standards in order to function properly. In fact, it may seem to function better than the jQuery version that tvanfosson posted which seems to do the swap only twice.

    What standards peculiarities does it rely on?


    insertBefore
    Inserts the node newChild before the existing child node refChild. If
    refChild is null, insert newChild at
    the end of the list of children.
    If newChild is a DocumentFragment object, all of its children are
    inserted, in the same order, before
    refChild. If the newChild is already
    in the tree, it is first removed.

    ReplyDelete
  5. Jquery approach mentioned on the top will work.
    You can also use JQuery and CSS .Say for e.g on Div one you have applied class1 and div2 you have applied class class2 (say for e.g each class of css provides specific position on the browser), now you can interchange the classes use jquery or javascript (that will change the position)

    ReplyDelete
  6. Sorry for bumping this thread
    I stumbled over the "swap DOM-elements" problem and played around a bit

    The result is a jQuery-native "solution" which seems to be really pretty (unfortunately i don't know whats happening at the jQuery internals when doing this)

    The Code:
    $('#element1').insertAfter($('#element2'));

    The jQuery documentation says that insertAfter() moves the element and doesn't clone it

    ReplyDelete
  7. If you have jQuery on the page, this post should answer your question.

    ReplyDelete

Post a Comment

Popular posts from this blog

Why is this Javascript much *slower* than its jQuery equivalent?

I have a HTML list of about 500 items and a "filter" box above it. I started by using jQuery to filter the list when I typed a letter (timing code added later): $('#filter').keyup( function() { var jqStart = (new Date).getTime(); var search = $(this).val().toLowerCase(); var $list = $('ul.ablist > li'); $list.each( function() { if ( $(this).text().toLowerCase().indexOf(search) === -1 ) $(this).hide(); else $(this).show(); } ); console.log('Time: ' + ((new Date).getTime() - jqStart)); } ); However, there was a couple of seconds delay after typing each letter (particularly the first letter). So I thought it may be slightly quicker if I used plain Javascript (I read recently that jQuery's each function is particularly slow). Here's my JS equivalent: document.getElementById('filter').addEventListener( 'keyup', function () { var jsStart = (new Date).getTime()...

Is it possible to have IF statement in an Echo statement in PHP

Thanks in advance. I did look at the other questions/answers that were similar and didn't find exactly what I was looking for. I'm trying to do this, am I on the right path? echo " <div id='tabs-".$match."'> <textarea id='".$match."' name='".$match."'>". if ($COLUMN_NAME === $match) { echo $FIELD_WITH_COLUMN_NAME; } else { } ."</textarea> <script type='text/javascript'> CKEDITOR.replace( '".$match."' ); </script> </div>"; I am getting the following error message in the browser: Parse error: syntax error, unexpected T_IF Please let me know if this is the right way to go about nesting an IF statement inside an echo. Thank you.