Reputation: 99
Let's say I have this page structure
<div id="line-value-container-1-1">
<button type="button" id="up_value_1_1">
<span class="icon-chevron-up"></span>
</button>
<button type="button" id="down_value_1_1">
<span class="icon-chevron-down"></span>
</button>
</div>
<div id="line-value-container-1-2">
<button type="button" id="up_value_1_2">
<span class="icon-chevron-up"></span>
</button>
<button type="button" id="down_value_1_2">
<span class="icon-chevron-down"></span>
</button>
</div>
<div id="line-value-container-1-3">
<button type="button" id="up_value_1_3">
<span class="icon-chevron-up"></span>
</button>
<button type="button" id="down_value_1_3">
<span class="icon-chevron-down"></span>
</button>
</div>
Let'say when for example when button with id="up_value_1_3" is clicked, I want to move the its parent div up onde element so it's stays before div with id="line-value-container-1-2" like this:
<div id="line-value-container-1-1">
<button type="button" id="up_value_1_1">
<span class="icon-chevron-up"></span>
</button>
<button type="button" id="down_value_1_1">
<span class="icon-chevron-down"></span>
</button>
</div>
<div id="line-value-container-1-3">
<button type="button" id="up_value_1_3">
<span class="icon-chevron-up"></span>
</button>
<button type="button" id="down_value_1_3">
<span class="icon-chevron-down"></span>
</button>
</div>
<div id="line-value-container-1-2">
<button type="button" id="up_value_1_2">
<span class="icon-chevron-up"></span>
</button>
<button type="button" id="down_value_1_2">
<span class="icon-chevron-down"></span>
</button>
</div>
This problem is easely solved with JQuery insertBefore() function.
Now Imagine I want to exchange id's between this two moved div's, when I say for example:
$("#line-value-container-1-2".attr('id', "#line-value-container-1-3");
$("#line-value-container-1-3".attr('id', "#line-value-container-1-2");
This simple exchange does not works because after the first id change the document becames an invalid HTML, because there's two elements with same id, and the second statement will just select the first element with that id which is the id previously changed.
Conclusion all changes make no changes. How can I solve this problem?
Upvotes: 1
Views: 1465
Reputation: 30557
You can use custom data-*
attributes like
$("#line-value-container-1-2").attr('data-id', "line-value-container-1-3");
$("#line-value-container-1-3").attr('data-id', "line-value-container-1-2");
$("#line-value-container-1-2,#line-value-container-1-3").each(function(){
$(this).attr('id', $(this).attr('data-id'));
});
Upvotes: 2
Reputation: 17952
You can temporarily store the first reference in a variable while you make the change, like this:
var temp = $('#line-value-container-1-2');
$('#line-value-container-1-3').attr('id', 'line-value-container-1-2');
temp.attr('id', 'line-value-container-1-3');
Upvotes: 1