user2478884
user2478884

Reputation: 3

Buttons that need to change their .innerHTML but they are made in a loop so they end up having the same id

I am writing a table tree in javascript for xml files, and I need button for each . When this button is clicked it needs to have its text change from "-" to "+" and vice a versa. I know normally the following code would work;

function change()
{
    if(document.getElementsById("myButton").innerHTML == "-"){
        document.getElementById("myButton").innerHTML = "+";
    }
    else{
        document.getElementById("myButton").innerHTML = "-";
    }
}

The reason I cannot just use this is because the buttons are created in a loop so they all have the same Id.

If you could help me to either make it so each time the button is made its Id has an incrementing number appended to it, or have another means of doing the above code it would be helpful.

Upvotes: 0

Views: 117

Answers (2)

Anthony Grist
Anthony Grist

Reputation: 38345

There's no need to use an ID at all; instead pass the element to modify as an argument to the change function. The function would now look like this:

function change(element)
{
    if(element.innerHTML == "-"){
        element.innerHTML = "+";
    }
    else{
        element.innerHTML = "-";
    }
}

Then, when you create your buttons, the onclick attribute would look like this:

onclick="change(this);"

Upvotes: 1

Dylan N
Dylan N

Reputation: 517

When you are looping through creating each button, create a counter variable, or use the variable from the for loop, and each loop increment it by 1 and append that to the ID.

for(var i = 0; i < some_number; i++){
  var ID = "myButton"+i;
  //Other code
}

Upvotes: 1

Related Questions