1

I have two div's

    <div id="one">xyz</div>
    <div id="two">abc</div>
    <input id="reverse" type="button" value="Reverse" />

On click of the button, the the id's of the div needs to get interchanged.

    $('#one').attr('id', 'two');
    $('#two').attr('id', 'one'); 

would obviously be false, can anyone help me regarding this?

Krishh
  • 4,111
  • 5
  • 42
  • 52

3 Answers3

2

Something like this should work:

$('#reverse').click(function() {
    var $one = $('#one');
    var $two = $('#two');
    $one.attr('id', 'two');
    $two.attr('id', 'one');
});

Demo: http://jsfiddle.net/ambiguous/9zNq6/

If you're really paranoid then:

$('#reverse').click(function() {
    var $one = $('#one');
    var $two = $('#two');
    $one.removeAttr('id');
    $two.attr('id', 'one');
    $one.attr('id', 'two');
});

Demo: http://jsfiddle.net/ambiguous/uQnpY/

mu is too short
  • 426,620
  • 70
  • 833
  • 800
1

Cache the selector first so it holds a reference to the element, then swap the id attributes.

var one = $('#one');
$('#two').attr('id', 'one');
one.attr('id', 'two');

jsFiddle.

alex
  • 479,566
  • 201
  • 878
  • 984
0

I don't think you should be messing around with IDs in that fashion; if it is a matter of positioning, using a class variable makes more sense. Are you sure you can't use addclass/removeclass for your purposes?

Out of curiousity, would switching the content of the two be sufficient?

If you wanted to switch the content, it would be pretty simple:

    function switch_contents(){
            var one_contents = $('#one').html();
            $('#one').html($('two').html());
            $('#two').html(one_contents);
    }

If you are really interested in actually switching the IDs, there is an example with switching IDs over here; Changing an element's ID with jQuery

Community
  • 1
  • 1
jbm
  • 116
  • 3