I hope you can help me with a little problem. With my code I want to rename the element id's of my ul list, which are sorted by jquery sortable, but its not working properly. Sometimes it's working, but sometimes there's just an error: "Uncaught TypeError: Cannot read property 'id' of null" and it's renaming like: 1-2-3-4-5-6-6-8 .Maybe you can help me out.
Here's my ul:
<ul class="example">
<li id="1" class="example"></li>
<li id="2" class="example"></li>
<li id="3" class="example"></li>
<li id="4" class="example"></li>
<li id="5" class="example"></li>
<li id="6" class="example"></li>
</ul>
js for jquery sortable:
$('.example').sortable();
and here's my js for getting actual index and renaming li id:
function myFunction(){
var lenght = $(".example").length;
lenght = lenght -1;
for (var i=1; i<=lenght; i++){
var newIn = $('#'+i).index();
newIn = newIn +1;
var inold = document.getElementById(i).id;
if(newIn != inold){
var change = document.getElementById(i).id = newIn;
}
}
}
Thank you for giving me a hint!
Thanks for your hint CBroe! Its working like a charm now!
function myFunction(){
$(".example").each(function(i) {
var row = $(this)
row.attr('id', '' + i);
});
}
this error occurred when you have a list of duplicate id's or not a continues id's like(3,2,4,1,6) here '5' is missing and you are just replacing id by accessing sequential number that is 'i' so when i will reach to 5 then "document.getElementById(i).id" this will give you '-1' because there is no li with id=5. i hope this code will help you for your problem.
function myfunction(){
$("li.example").each(function() {
var currentId = $(this).attr("id"); //id of each li
var newIn = $(this).index(); //index of each li starts from 0
newIn++;
if(currentId!==newIn)
{
$(this).attr("id",newIn);
}
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.