Dynamically setting div id in JavaScript or jQuery

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

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

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

    $('#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>
    
    0 讨论(0)
  • 2020-12-15 12:18

    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.

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

    Try this..

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

    divid.id = 'q5';

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

    In JavaScript

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

    In jQuery

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

    JSFiddle example

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

    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 讨论(0)
  • 2020-12-15 12:27

    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/

    0 讨论(0)
提交回复
热议问题