Dynamically setting id div in javascript or jQuery
How to set dynamic div id? Here is my code:
<div id="q1"></div> <div id="q2"></div> <div id="q3"></div> <div id="q4"></div> <div id="q5"></div> Now I want to set the id q4 div to q1, much like in JavaScript. How can I do this in JavaScript or jQuery?
I have tried this.
document.getElementById("q4").id = "q1"; document.getElementById("q2").id = "q5"; but it says the object is null or undefined.
Thanks. Chakri.
Using jquery:
dynamically set one by one:
var idCount = 1; $('div').each(function() { $(this).attr('id', 'q' + idCount); idCount++; }); to change what you want:
$('div#q4').attr('id', 'q1'); $('div#q2').attr('id', 'q5'); $('#q1').attr('id', 'q4') I think ...
EDIT:
If it still does not work, try putting this before </body> :
<script> $(document).ready(function(){ $('#q1').attr('id', 'q4') }); </sript> First of all, you give id to the id element that has already been set for some element before, which does not suit you, you cannot have more than one identifier in your DOM. In any case, the code will be something like
var element = document.getElementById('q4'); element.setAttribute('id', 'q7'); if(document.getElementById('q7').innerHTML = "All is well") alert(document.getElementById('q7').innerHTML); //to check if the new id has been set correctly Fiddle http://jsfiddle.net/kmSHB/
Your code is fine, which means if it doesn’t work, you are probably running JavaScript before these elements are defined in the DOM. Try moving the script block below these elements (for example, at the bottom of the page) or put your code in a boot / ready DOM handler.
Edit: I don’t know why it voted, but anything. If you want to do this in jQuery, waiting for a DOM ready event, this should work:
$(function() { $('#q4').attr('id', 'q1'); $('#q2').attr('id', 'q5'); }); Please note that the important part here is not that setting the id is done in jQuery or vanilla JavaScript - the important part is that we are waiting for the DOM to be ready for manipulation.
Your code is working fine. Except that after that you will have 2 divs with the same id. Thus, you will encounter problems if you try to get q1 again.
in jQuery you can do this:
$('#q4').attr('id', 'q1'); However, note that now you will leave invalid markup, as you cannot use the same identifier more than once in the document.