我对通过createHTMLDocument构建的对象getElementsByClassName有问题。在尝试createHTMLDocument之前,我有createElement('div'),这工作得很好,但当createHTMLDocument
时并非如此
setTimeout(function() {
console.log('Starting...');
//var copy = document.createElement('div');
var copy = document.implementation.createHTMLDocument('virtual');
copy.innerHTML = document.getElementById('test').innerHTML;
//console.log(copy.innerHTML);
var r = copy.getElementsByClassName('removeOnSave');
console.log('seen ' + r.length);
for (var i = r.length - 1; i >= 0; i--) r[i].parentNode.removeChild(r[i]);
var contentsTx = copy.innerHTML;
document.getElementById('output').value = contentsTx;
}, 1000);
<h3>Load HTML from some content while trying not to trigger network calls</h3>
<div id="test">
Lorem ipsum
<img src="https://cdn.speakerscorner.co.uk/files/media/public/image/richard-ayoade-xsq.jpg">
Lorem ipsum <div class="removeOnSave">REMOVE ME</div>
</div>
<textarea id="output" style="width:100%; height:200px"></textarea>
(也可以在https://jsfiddle.net/Abeeee/deg3846s/10/上获得JSFiddle演示)
我哪里错了?
问题是您应该将innerHTML
设置在新创建的文档的主体上,即copy.body.innerHTML = document.getElementById('test').innerHTML;
。我想你自己能解释为什么,所以我就不详细解释了。
setTimeout(function() {
console.log('Starting...');
//var copy = document.createElement('div');
var copy = document.implementation.createHTMLDocument('virtual');
copy.body.innerHTML = document.getElementById('test').innerHTML;
//console.log(copy.innerHTML);
var r = copy.getElementsByClassName('removeOnSave');
console.log('seen ' + r.length);
for (var i = r.length - 1; i >= 0; i--) r[i].parentNode.removeChild(r[i]);
var contentsTx = copy.body.innerHTML;
console.log('contentsTx=',contentsTx );
document.getElementById('output').value = contentsTx;
}, 1000);
<h3>Load HTML from some content while trying not to trigger network calls</h3>
<div id="test">
Lorem ipsum
<img src="https://cdn.speakerscorner.co.uk/files/media/public/image/richard-ayoade-xsq.jpg">
Lorem ipsum <div class="removeOnSave">REMOVE ME</div>
</div>
<textarea id="output" style="width:100%; height:200px"></textarea>