简体   繁体   中英

Javascript dynamic button id

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?

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 
}

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/

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM