Home > Software engineering >  Javascript dynamic button id
Javascript dynamic button id

Time:11-24

I have dynamically made a button using Javascript, now i need to give that button an ID, i have tried with

buttonElementBlokkeer.setAttribute("id", "buttonBlokkeer");

& 

buttonElementBlokkeer.id = "buttonBlokkeer"

Both is not working. The buttons are nested in a section that already has an id, could this be a reason why it is not working?

CodePudding user response:

HTML

<div id="divId"></div>

JS

for (i = 1; i <= 3; i  ) {
    var btn = document.createElement("BUTTON");// create       button using java script
    btn.className = "btnsize";
    btn.id = "btnid"  i;
    var txt = document.createTextNode("Buttons" i);//creat text on button
    btn.appendChild(txt);//attached text on button
    document.getElementById("divId").appendChild(btn);//atache button with text in div 
}

CodePudding user response:

Try this:

let button = document.createElement('input');
button.setAttribute('type', 'BUTTON');
button.setAttribute('ID', 'buttonBlokkeer');
button.setAttribute('value', 'BUTTON');
button.setAttribute('onclick', 'test()');
document.body.appendChild(button);


function test() {
  console.log("BUTTON !");
  alert("BUTTON !");
}

https://jsfiddle.net/onw2esyg/

CodePudding user response:

This is working for me. You can use getElementsByClassName() function if you want to access by class name.

<button id="changeId">Button1</button>
<button onclick="update()">Update</button>
    
<script>
function update() {
   document.getElementById("changeId").id = "IdUpdated";
}
</script>
  • Related