Search code examples
javascripthtmlgetelementsbytagnameclonenode

how to 'getelementsbytagname.onclick'


I am trying to get my cloneNode to append the input tag and give it a new onclick value. Its just the input.onclick = function(){clicker(iden);}; that doesn't work. The sole purpose of this example is to change the onclick tag like I managed to change the ID. Can anyone please help?

Script

<script>
  iden = 0

  function clicker(x) {
    iden++

    var ent = document.getElementById('ent').cloneNode(true);

    ent.id = "ent"+iden;
    var input = ent.getElementsByTagName('input')[0];

    input.id = "inp"+iden;
    input.onclick = function(){clicker(iden);};

    document.body.appendChild(ent);
  }
</script>

Body

<body>
  <div id="ent">
    <input id="inp" onclick="clicker()">
  </div>
<body>

Solution

  • Removing the

    function () {
    

    At the bottom of your tag fixed it for me

    <html>
    <body>
        <script>
        iden = 0
    
        function clicker(x) {
            iden++
    
            var ent = document.getElementById('ent').cloneNode(true);
    
            ent.id = "ent"+iden;
            var input = ent.getElementsByTagName('input')[0];
    
            input.id = "inp"+iden;
            input.onclick = function(){
                clicker(iden);
            };
    
            document.body.appendChild(ent);
        }
        </script>
        <div id="ent">
        <input id="inp" onclick="clicker()">
        </div>
    </body>
    </html>