How to unlink elements from objects?

2

I have the following function

addPerson = function(id, name) {
    people[id] = name;

    console.log(people[id].parentNode); // Exibe corretamente
    console.log(name.parentNode); // Exibe corretamente

    name.parentNode.removeChild(name);

    console.log(people[id].parentNode); // Deixa de exibir
    console.log(name.parentNode); // Deixa de exibir

    if(!name.previousElementSibling) {
        $(name.parentNode).append(name);
    }else{
        name.previousElementSibling.insertAfter(name);
    }
};

-

The parameter name references an element in DOM , when the function is called people[id] it receives this element, however when executing some example deletion of the element, the reference loses access to the methods, eg% , I tried to use parentNode of clone , but it did not work.

Is there any way to clone the object, keep the native methods and unlink it from the element in J-query ?

    
asked by anonymous 28.09.2017 / 16:28

1 answer

2

You do not need to clone the element unless you need several of the same. You can use var semPai = el.parentElement.removeChild(el); and stay with the element "on hand" outside the DOM.

var div = document.querySelector('div');
var btn = div.firstElementChild;
btn.addEventListener('click', function() {
  console.log('Clicado!');
});

var semPai = btn.parentElement.removeChild(btn);
console.log(div.children.length); // vazio
console.log(semPai.parentNode); // sem pai!

btn.click();
<div><button>Clica-me</button>
</div>

If you need to know the initial position I suggest you create an object to store this information like this:

var objs = [];

var div = document.querySelector('div');
var btn = div.firstElementChild;
btn.addEventListener('click', function() {
  console.log('Clicado!');
});

// guardar para mais tarde
objs.push({
  el: btn,
  previousSibling: btn.previousElementSibling || {},
  parent: btn.parentElement
});

btn.parentElement.removeChild(btn);
console.log(div.children.length); // 0 => vazio
console.log(btn.parentNode); // null => sem pai! está fora do DOM

// depois mais tarde...
objs[0].parent.insertBefore(objs[0].el, objs[0].previousSibling.nextSibling);
<div><button>Clica-me</button>
</div>
    
28.09.2017 / 16:34