How do I save/restore an object's location in the DOM tree?

前端 未结 1 390
春和景丽
春和景丽 2021-02-11 04:05

If I have the following html:

  • test
  • special
  • test
<
1条回答
  •  南笙
    南笙 (楼主)
    2021-02-11 04:16

    To save an object's position, you can just save the DOM reference to the sibling before it. If there is no sibling before it, then save the parent.

    function saveLocation(element) {
        var loc = {};
    
        var item = $(element).prev();
        loc.element = element;
        if (item.length) {
            loc.prev = item[0];
        } else {
            loc.parent = $(element).parent()[0];
        }
        return(loc);
    }
    

    Then, to restore:

    function restoreLocation(loc) {
        if (loc.parent) {
            $(loc.parent).prepend(loc.element);
        } else {
            $(loc.prev).after(loc.element);
        }
    }
    

    0 讨论(0)
提交回复
热议问题