Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DOM equivalent to jQuery `.detach()`?

Tags:

javascript

dom

I’m trying to remove an input field by clicking an “X button”. After it is removed it will not post its value when the form is submitted. A “+ button” appears that allows the user to add said input again. The input has an onclick event that opens a calendar and after reattaching, the calendar does not open on click anymore. I can’t use jQuery.

adderBtn.onclick = function (e) {
    var elem = that.hiddenElems.shift();
    that.collectionItemContainer.append(elem);
}

removerBtn.onclick = function (e) {
    collectionItemElem.remove();
    that.hiddenElems.push(collectionItemElem);
}

The question is how do I remove and reattach DOM nodes without losing the Events.

like image 454
иikolai Avatar asked Feb 05 '18 15:02

иikolai


2 Answers

When you remove an element, as long as you keep a reference to it, you can put it back. So:

var input = /*...code to get the input element*/;
input.parentNode.removeChild(input); // Or on modern browsers: `input.remove();`

later if you want to put it back

someParentElement.appendChild(input);

Unlike jQuery, the DOM doesn't distinguish between "remove" and "detach" — the DOM operation is always the equivalent of "detach," meaning if you add the element back, it still has its handlers:

Live Example:

var input = document.querySelector("input[type=text]");
input.addEventListener("input", function() {
  console.log("input event: " + this.value);
});
input.focus();
var parent = input.parentNode;
document.querySelector("input[type=button]").addEventListener("click", function() {
  if (input.parentNode) {
    // Remove it
    parent.removeChild(input);
  } else {
    // Put it back
    parent.appendChild(input);
  }
});
<form>
  <div>
    Type in the input to see events from it
  </div>
  <label>
    Input:
    <input type="text">
  </label>
  <div>
    <input type="button" value="Toggle Field">
  </div>
</form>

If you remove the element without keeping any reference to it, it is eligible for garbage collection, as are any handlers attached to it (provided nothing else refers to them, and ignoring some historic IE bugs in that regard...).

like image 137
T.J. Crowder Avatar answered Oct 21 '22 04:10

T.J. Crowder


To detach an element in function form:

function detatch(elem) {
    return elem.parentElement.removeChild(elem);
}

This will return the 'detached' element

like image 39
scagood Avatar answered Oct 21 '22 03:10

scagood