Question

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>
Was it helpful?

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>

OTHER TIPS

JS :

function clicker(iden) {  
    iden = (!iden) ?  '' : iden;


    var ent = document.getElementById('ent'+ iden ).cloneNode(true);
    iden++;
    ent.id = "ent" + iden;

    var input = ent.childNodes[1];
    input.id = "inp" + iden;

    input.onclick = function () {
        clicker(iden);
    };

    document.body.appendChild(ent);
}

HTML :

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

If you're only trying to change the onlick attribute using setAttribute would work:

input.setAttribute("onclick", "clicker(" + iden + ");");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top