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

时间:2015-05-18 10:18:32

标签: javascript html dom range selection

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

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

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的副本中删除它们。我已经制作了这样的副本:var fullDocument = $('html').clone();我怎么能做到这一点?

1 个答案:

答案 0 :(得分:0)

在克隆之前动态地向加载的所有元素添加类或数据属性,以便您有一个引用点,然后获取共同祖先上的类或数据属性并将其从克隆中删除。如果你愿意,我可举个例子吗?沿着这些方向 - 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);
相关问题