Home > Net >  Problems using getElementsByClassName with createHTMLDocument
Problems using getElementsByClassName with createHTMLDocument

Time:10-22

I'm having problems with getElementsByClassName against an object built through createHTMLDocument. Prior to trying createHTMLDocument I had createElement('div') and this worked fine, but not so when 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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

(A JSFiddle demonstrator is also available on https://jsfiddle.net/Abeeee/deg3846s/10/)

Where am I going wrong?

CodePudding user response:

The problem is that you shod set innerHTML on the body of the newly created document i.e. copy.body.innerHTML = document.getElementById('test').innerHTML;. I think you are able to explain yourself why, so I won't explain in details.

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>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related