I was trying to add an extra id of an element and wanted to change it after a duration. here is the code I have tried. what did I do wrong? Thanks in advance
var ids = [
"cs-bg-img",
"cs-bg-img1"
]
$(function () {
var i = 0;
$("#cs-banner-background").attr('id', ids[i]);
setInterval(function () {
i ;
if (i == ids.length) {
i = 0;
}
$("#cs-banner-background").attr('id', ids[i]);
}, 2300);
});
CodePudding user response:
Try this:
$(function () {
var i = 0;
var idChanged= document.getElementById("cs-banner-background");
idChanged.id=ids[i]
setInterval(function () {
i ;
if (i == ids.length) {
i = 0;
}
idChanged.id=ids[i]
}, 2300);
});
CodePudding user response:
I think that your problem is the ID itself, in the first change it may actually work but after that when you ask jquery for the #cs-banner-background element it won't find anything since you actually changed it's id a few lines above to "cs-bg-img" (which is ids[0])
After your change you. should use ids[0] as ID selector to find again that element
If you are trying to change it's ID to get some different style i suggest you to add that element another class in your HTML so that you can simply search it by class or just move the CSS associated with the IDS to some class and instead of changing the ID with every time interval you could simply change it's classes. Just my 2 cents