Dynamically setting div id in JavaScript or jQuery

后端 未结 8 1806
夕颜
夕颜 2020-12-15 11:43

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

<
相关标签:
8条回答
  • 2020-12-15 12:32

    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.

    0 讨论(0)
  • 2020-12-15 12:33

    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');
    
    0 讨论(0)
提交回复
热议问题