Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery swap content between two DOM elements

I have two span tags. I'd like to swap the content between them once the user clicks on one of them. If the user clicks once more, swap the content again and so on.

$(".sectionTitleText").livequery("click", function () {
        var editor = $(this).attr("data-edit-id");
        var viewer = $(this).attr("data-view-id");

        //Swap code
});
like image 766
Carlos Blanco Avatar asked Nov 17 '25 14:11

Carlos Blanco


1 Answers

If both nodes are the only children of the same parent, just do this:

$('#parent').prepend($('#parent').children().last());

This should take whichever element is currently last, and make it first.

See http://jsfiddle.net/alnitak/wt4VZ/ for demo.

If that doesn't apply, try:

var el1 = $('#element1');
var el2 = $('#element2');
var tag1 = $('<span/>').insertBefore(el1); // drop a marker in place
var tag2 = $('<span/>').insertBefore(el2); // drop a marker in place
tag1.replaceWith(el2);
tag2.replaceWith(el1);

The idea here is that the two temporary spans just act as place holders into which the original elements will be dropped, without serialising or otherwise messing with those elements.

See http://jsfiddle.net/alnitak/bzKXn/ for a demo of that.

like image 111
Alnitak Avatar answered Nov 20 '25 03:11

Alnitak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!