How to set the div id dynamically? Here is my code:
<
Your code is fine, which means that if it's failing, you're probably running the JavaScript before those elements have been defined in the DOM. Try moving the script block to below those elements (e.g., the bottom of the page), or place your code in a DOM load/ready handler.
$(function() {
$('#q4').attr('id', 'q1');
$('#q2').attr('id', 'q5');
});
Please note that the important part here isn't the fact that setting the id is done in jQuery or vanilla JavaScript - the important part is that we're waiting until the DOM is ready for manipulation.
Using jquery:
set dynamically one by one:
var idCount = 1;
$('div').each(function() {
$(this).attr('id', 'q' + idCount);
idCount++;
});
to rearrange what you want:
$('div#q4').attr('id', 'q1');
$('div#q2').attr('id', 'q5');