Zhaf
Zhaf

Reputation: 1884

How to remove an element by id?

I just try a tutorial here on how to upload multiple form - http://www.maheshchari.com/multifile-upload/

Basically, it have a link to add a new input when it clicked. My question is, how to add another link to REMOVE the input?

Thanks for helping :)

Upvotes: 0

Views: 910

Answers (3)

Vijin Paulraj
Vijin Paulraj

Reputation: 4618

It's very simple,

document.getElementById("_id").parentNode.removeChild(document.getElementById("_id"));  

Upvotes: 0

Shailesh Jangir
Shailesh Jangir

Reputation: 395

please update you function add_file_field to

var file_counter = 0;
function add_file_field(){
    file_counter++;
    var container=document.getElementById('file_container');
    var file_field=document.createElement('input');
    file_field.name='images[]';
    file_field.type='file';
    file_field.id='file_'+file_counter;
    container.appendChild(file_field);
    var remove_field = document.createElement('a');
    remove_field.href = "javascript:removeById('"+'file_'+file_counter+"');removeById('"+'remove_field_'+file_counter+"');";
    remove_field.innerHTML = "Remove')";
    remove_field.id = 'remove_field_'+file_counter;
    var br_field=document.createElement('br');
    container.appendChild(br_field);
}

this create a and also add function removeById in you javascript so that when any one clicks on remove button then the file type field will remove. which is posted in previous post also

function removeById(id) {
  var element = document.getElementById(id);
  // A bit of robustness helps...
  if (element && element.parentNode) {
    element.parentNode.removeChild(element);
  }
}

Upvotes: 0

RobG
RobG

Reputation: 147363

You can remove an element that you know the ID of using:

function removeById(id) {
  var element = document.getElementById(id);

  // A bit of robustness helps...
  if (element && element.parentNode) {
    element.parentNode.removeChild(element);
  }
}

Upvotes: 2

Related Questions