开发者

Dynamically setting div id in JavaScript or jQuery

开发者 https://www.devze.com 2023-04-06 21:58 出处:网络
How to set the div id dynamically? Here is my code: <div id=\"q1\"></div> <div id=\"q2\"><开发者_Python百科/div>

How to set the div id dynamically? Here is my code:

<div id="q1"></div>
<div id="q2"><开发者_Python百科/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.


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');


$('#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>


First of all, you are giving the id to an element an id which is already given to some element before, that's not a right thing to do you can't have more than one id in your DOM. Anyway the code would 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 works fine. Except that after that you will have 2 divs with the same id. So you will run to problems if you try to get q1 again.


Try this..

var divid = document.getElementById('q1');

divid.id = 'q5';


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.


Edit: not sure why this is being down voted, but whatever. If you want to do this in jQuery while waiting for the DOM ready event, this should work:

$(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.


In JavaScript

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

In jQuery

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

JSFiddle example


in jQuery you could do this:

$('#q4').attr('id', 'q1');

However, note that that will now leave you with invalid markup, as you can't use the same ID more than once in a document.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号