Zuned Ahmed
Zuned Ahmed

Reputation: 1387

How should change the ID of DIV in jQuery

I have to swap the div.

Swapping is working fine( I am using Jquery Swap Plugin for that). After swap I want to swap the ID of DIVs too.

Please find JQuery Code. Kindly help me out how should I swap the DIV IDs.

 $(".arrowIMG").click(function() {
                    var arr = this.id.split("_");
                    if(arr[0] == 'down'){

                        var div1 = $('#'+'div_' +arr[1]);
                        var next = (parseInt(arr[1]) + 1);
                        alert(next)
                        var div2 = 'div_' + next;

                        div1.swap({
                        target: div2, 
                        opacity: "0.5",
                        speed: 1000, 
                        callback: function() { 
                         //Now Here i want to swap the id of div (div1 and dev2)

                        }
                    });

                    }else if(arr[0] == 'up') {
                        alert('up');
                    }

                }); 

Kindly help me out the way to swap the DIV IDs.

Upvotes: 2

Views: 140

Answers (3)

Niranjan Singh
Niranjan Singh

Reputation: 18290

Use jQuery .attr() to Get the value of an attribute for the first element in the set of matched elements.

Check this:

<div id="my" > s,dfsd </div>  

<div id="src" class="div1">       
    src
</div>
<div id="dest" class="div2">
    dest
</div>

jQuery Code:

$("#my").attr('id','mynewid');
$("#mynewid").html("this new content");

var temp = $(".div1").attr('id');
$(".div1").attr('id',$(".div2").attr('id'));
$(".div2").attr('id', temp);

Check this jsFiddle

Adjust your click event behavior using this code snippet. in your function() code you have already accessed those elements so you can directly access the id of those elements.

var temp = div1.attr('id');
    div1.attr('id',div2.attr('id'));
    div2.attr('id', temp);

Upvotes: 0

Mithun Satheesh
Mithun Satheesh

Reputation: 27855

callback: function() { 

    var div2selector = $('#'+div2); //making both selectors in same format as div2='div_' + next
    var tempid = div1.attr('id');
    div1.attr('id',div2selector.attr('id'));
    div2selector.attr('id',tempid );

                    }

EDIT:

div1 and div2 are not in same format. so made similar

Upvotes: 1

cmpolis
cmpolis

Reputation: 3051

I'm not sure exactly what the desired behavior of your function is - but the following should work to change an ID:

$(element).attr('id', 'new_id');

Upvotes: 2

Related Questions