Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically setting div id in JavaScript or jQuery

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.

like image 417
Chakradhar Avatar asked Sep 22 '11 12:09

Chakradhar


People also ask

How to add div id dynamically in jQuery?

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.

What is div id in JavaScript?

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.

Can we add ID using jQuery?

We can add an id to an HTML element using jQuery very easily by combining the attr() method with a click event.


2 Answers

In JavaScript

var yourElement = document.getElementById('originalID');
yourElement.setAttribute('id', 'yourNewID');

In jQuery

$('#originalID').attr('id', 'yourNewID');

JSFiddle example

like image 52
danefondo Avatar answered Oct 12 '22 00:10

danefondo


$('#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>
like image 37
Ernestas Stankevičius Avatar answered Oct 11 '22 23:10

Ernestas Stankevičius