Подтвердить что ты не робот

Jquery: switch Элементы в DOM

Какой лучший способ переключить два элемента в DOM с помощью jquery?

<div id="switchme2">some other elements in here....</div>
<div class="some other elements"></div>
<div id="switchme1">some other elements in here....</div>

должен заканчиваться на:

<div id="switchme1">some other elements in here....</div>
<div class="some other elements"></div>
<div id="switchme2">some other elements in here....</div>
4b9b3361

Ответ 1

Вы получите людей, которые говорят вам использовать jQuery before, after и т.п., но будьте осторожны, что может испортить вещи, если есть текстовые узлы по обе стороны от любого элемента (подробнее об этом ниже).

Из-за этого (и для людей, не использующих jQuery) вы можете просто напрямую использовать DOM:

function swapElements(elm1, elm2) {
    var parent1, next1,
        parent2, next2;

    parent1 = elm1.parentNode;
    next1   = elm1.nextSibling;
    parent2 = elm2.parentNode;
    next2   = elm2.nextSibling;

    parent1.insertBefore(elm2, next1);
    parent2.insertBefore(elm1, next2);
}

Обратите внимание, что это нормально, если ссылочный элемент (next1 или next2 выше) равен null; insertBefore обрабатывает это правильно (добавив в конец родителя, например appendChild).

Использование в сочетании с jQuery:

swapElements($("#switchme1")[0], $("#switchme2")[0]);

Живой пример:

jQuery(function($) {
  
    function swapElements(elm1, elm2, elm3, elm4, elm5) {
        var parent1, next1,
            parent2, next2,
            parent3, next3,
            parent4, next4,
            parent5, next5;

        parent1 = elm1.parentNode;
        next1   = elm1.nextSibling;
        parent2 = elm2.parentNode;
        next2   = elm2.nextSibling;
        parent3 = elm3.parentNode;
        next3   = elm3.nextSibling;
        parent4 = elm4.parentNode;
        next4   = elm4.nextSibling;
        parent5 = elm5.parentNode;
        next5   = elm5.nextSibling;

        parent1.insertBefore(elm2, next1);
        parent2.insertBefore(elm3, next2);
        parent3.insertBefore(elm4, next3);
        parent4.insertBefore(elm5, next4);
        parent5.insertBefore(elm1, next5);
    }

    $("#btnSwitch").click(function() {
        swapElements($("#switchme1")[0], $("#switchme2")[0], $("#switchme3")[0], $("#switchme4")[0], $("#switchme5")[0]);
    });
  
});
first text node
<div id="switchme1">this is <strong>switchme1</strong> with <strong>some other elements</strong> <em>in here<div>test</div></em></div>
second text node
<div id="switchme2">this is <strong>switchme2</strong> with <strong>some other elements</strong> <em>in here</em></div>
<div id="switchme3">this is <strong>switchme3</strong> with <strong>some other elements</strong> <em>in here</em></div>
<div id="switchme4">this is <strong>switchme4</strong> with <strong>some other elements</strong> <em>in here</em></div>
<div id="switchme5">this is <strong>switchme5</strong> with <strong>some other elements</strong> <em>in here</em></div>
third text node
<input type="button" id="btnSwitch" value="Switch Em!">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Ответ 2

См. этот вопрос переполнение стека.

В основном говорится:

jQuery("#element1").before(jQuery("#element2"));

или

jQuery("#element1").after(jQuery("#element2"));

Красивая а? - Кредит лот.