How to set the div id dynamically? 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 q4 div id to q1 something like that in JavaScript. How can I do that in JavaScript or jQuery?
I have tried this.
document.getElementById("q4").id = "q1";
document.getElementById("q2").id = "q5";
but it is saying that the object is null or undefined.
Thanks. chakri.
jQuery example to dynamically add a div on page In this example, we have a div with id board and a button to add new divs into this board. In $(document). ready() we have bound an event listener to click event, which means when the user will click on this button, new divs will be created and added into the board.
The <div> tag defines a division or a section in an HTML document. The <div> tag is used as a container for HTML elements - which is then styled with CSS or manipulated with JavaScript. The <div> tag is easily styled by using the class or id attribute.
We can add an id to an HTML element using jQuery very easily by combining the attr() method with a click event.
var yourElement = document.getElementById('originalID');
yourElement.setAttribute('id', 'yourNewID');
$('#originalID').attr('id', 'yourNewID');
JSFiddle example
$('#q1').attr('id', 'q4')
it soulde work I think...
EDIT:
If it still doesnt work try put this before </body>
:
<script>
$(document).ready(function(){
$('#q1').attr('id', 'q4')
});
</sript>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With