temporarily removing and later reinserting a DOM element?

前端 未结 4 1357
囚心锁ツ
囚心锁ツ 2021-02-18 20:25

Is there some jquery magic that will let me do the following:

[0- define some element in HTML (eg, a unchecked checkbox)]

1- update its DOM element by s

4条回答
  •  日久生厌
    2021-02-18 21:04

    Just remove the element from the document and keep a reference to it. There's no need to clone it.

    var el;
    
    function removeEl() {
        el = $("#myElement")[0]; // Get the element itself
        el.parentNode.removeChild(el);
    }
    
    function reinsertEl(node) {
        node.appendChild(el);
    }
    

    As an aside since you mentioned it in your example, it's much simpler, clearer and faster to set the checked property of a checkbox directly rather than use attr(). There's no need to involve attributes at all and indeed jQuery's attr() usually doesn't. Just do $("#myElement")[0].checked = true;. It works in all mainstream browsers.

提交回复
热议问题