chitoiu daniel
chitoiu daniel

Reputation: 107

How to change div id dynamically

Maybe you can help me with this:

I have a function that ads a div by a button click. Any div contains a checkbox and a text field. If the checkbox is checked the text field is green, if not, the text field is red.

I don't know how to assign a dynamic div name for the "procedure" div, as the counter, like id = procedure1, id=procedure2... and then access the background color as procedure1.style.backgroundColor...

Thank you!

var counter = 1;

function addInput(divName) {
    var newdiv = document.createElement('div');
    newdiv.innerHTML = "<input type='checkbox' id='check' onclick='if(this.checked){procedure.style.backgroundColor=`green`;}
          else {procedure.style.backgroundColor=`red`;}'><input type='text' id='procedure'>";
    document.getElementById(divName).appendChild(newdiv);
    counter++;
}

Upvotes: 0

Views: 1899

Answers (3)

RBoschini
RBoschini

Reputation: 506

you can use jquery to do this

to set: $('#myObj').attr('id','NEWID');

or $('#myObj').prop('id','NEWID');

to get : $('#myObj').attr('id');

Upvotes: 0

Dan Prince
Dan Prince

Reputation: 29989

If you make the elements with document.createElement rather than with a string, then you can use setAttribute.

var dynamicId = 'someId';
element.setAttribute('id', dynamicId);

So for your example

var input = document.createElement('input');
input.setAttribute('type', 'checkbox');
input.setAttribute('id', 'check');
input.addEventListener('click', function() {
  if(this.checked) {
    // ...
  }
});

However, you might have noticed that using this approach you don't even need to use IDs. You can simply keep a reference to the elements you created with some variables.

var procedure1 = document.createElement('input');
var procedure2 = document.createElement('input');

procedure1.addEventListener('click', function() {
  // do something with procedure2
  procedure2.style.backgroundColor = 'red';
});

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816334

You shouldn't be using IDs for this at all. Traverse the DOM instead to find the corresponding <input>. In your specific case, the next sibling of the checkbox is the element you want to manipulate:

onclick='this.nextSibling.style.backgroundColor = this.checked ? "green" : "red";'

I also suggest to learn about other ways of binding event handlers, because inline event handlers have many disadvantages and using innerHTML like this makes your code more difficult to maintain.

Upvotes: 3

Related Questions