如何复制 HTML 文档并根据选择编辑副本,而不更改原始文档?

How do I copy an HTML document and edit the copy based upon the selection, without altering the original document?

我有一个 HTML 文档,我想根据标签是否在当前选择范围内,使用 Javascript 从中动态删除一些标签。但是,我不想更新页面上的实际文档,我想复制整个页面的 HTML 并编辑该副本。问题是,据我所知,我从 selection.getRangeAt(0) 获得的 Range 对象仍然指向原始文档。

我已经设法使用以下代码就地编辑原始文档:

var node = window.getSelection().getRangeAt(0).commonAncestorContainer;
var allWithinRangeOfParent = node.getElementsByTagName("*");

for (var i=0, el; el = allWithinRangeParent[i]; i++) {
    // The second parameter says to include the element 
    // even if it's not fully selected
    if (selection.containsNode(el, true) ) {
        el.remove();
    }
 }

但我想做的是以某种方式执行与删除元素相同的操作,但是从原始 HTML 的 copy 中删除它们。我已经制作了这样的副本:var fullDocument = $('html').clone();我怎样才能完成这个?

在克隆之前向加载的所有元素动态添加 class 或数据属性,以便您有一个参考点,然后获取共同祖先上的 class 或数据属性,然后从克隆中删除它。如果你愿意,我可以举个例子吗?按照这些思路 - http://jsfiddle.net/9s9hpc2v/ 不能正常工作,但你明白了要点。

$('*').each(function(i){
    $(this).attr('data-uniqueId', i);
});
var theclone = $('#foo').clone();


function laa(){
    var node = window.getSelection().getRangeAt(0).commonAncestorContainer;
    if(node.getElementsByTagName){

    var allWithinRangeOfParent =  $(node).find('*');
        console.log(allWithinRangeOfParent, $(allWithinRangeOfParent).attr('data-uniqueId'));
        $.each(allWithinRangeOfParent, function(){
            theclone.find('[data-uniqueId="'+$(this).attr('data-uniqueId')+'"]').remove();
        });
        console.log(theclone.html());
    }
}
$('button').click(laa);