简体   繁体   中英

DOM equivalent to jQuery `.detach()`?

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.

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...).

To detach an element in function form:

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

This will return the 'detached' element

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