How do I change the ID of a HTML element with JavaScript?

前端 未结 3 1436
無奈伤痛
無奈伤痛 2020-11-28 08:15

I am modifying the ID of an HTML div element client side with JavaScript. The following code works OK in Internet Explorer but not in Firefox/2.0.0.20. It does

相关标签:
3条回答
  • 2020-11-28 08:30

    It does work in Firefox (including 2.0.0.20). See http://jsbin.com/akili (add /edit to the url to edit):

    <p id="one">One</p>
    <a href="#" onclick="document.getElementById('one').id = 'two'; return false">Link2</a>
    

    The first click changes the id to "two", the second click errors because the element with id="one" now can't be found!

    Perhaps you have another element already with id="two" (FYI you can't have more than one element with the same id).

    0 讨论(0)
  • 2020-11-28 08:39

    That seems to work for me:

    <html>
    <head><style>
    #monkey {color:blue}
    #ape {color:purple}
    </style></head>
    <body>
    <span id="monkey" onclick="changeid()">
    fruit
    </span>
    <script>
    function changeid ()
    {
    var e = document.getElementById("monkey");
    e.id = "ape";
    }
    </script>
    </body>
    </html>
    

    The expected behaviour is to change the colour of the word "fruit".

    Perhaps your document was not fully loaded when you called the routine?

    0 讨论(0)
  • 2020-11-28 08:51

    You can modify the id without having to use getElementById

    Example:

    <div id = 'One' onclick = "One.id = 'Two'; return false;">One</div>
    

    You can see it here: http://jsbin.com/elikaj/1/

    Tested with Mozilla Firefox 22 and Google Chrome 60.0

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