简体   繁体   中英

How to get entire HTML from HTMLFragment ( like innerHTML )

If I have fragment = document.createDocumentFragment()
with some random Dom inside and I want to get the entire HTML ( excaly like innerHTML in regular element or document.documentElement.innerHTML in document object.

And after some text manipulation (by regex) return the HTML to the fragment how can I do that ?

I end up with that ugly solution :

        var helperDiv = document.createElement('div');
        helperDiv.appendChild(fragment)
        var innerHTML = helperDiv.innerHTML.replace(someRegExp,()=>values())
        helperDiv.innerHTML = innerHTML;
        var len = helperDiv.children.length;
        while(len--){
            fragment.appendChild( helperDiv.firstChild );
        }

So I appreciated a better way

2017 some update

I come with better solution with Range .

function fragmentInnerHTML(fragment, callback){
  var range = new Range();
  var helperDiv = document.createElement('div');
  helperDiv.appendChild(fragment);
  helperDiv.innerHTML = callback( helperDiv.innerHTML) 
  range.selectNodeContents(helperDiv);
  fragment.append( range.extractContents() );
  range.detach();
}

fragmentInnerHTML( fr, html => html.replace(/test(\d)/g,'test-$1') );

can be edited to be even fewer lines if needed

demo: https://jsfiddle.net/vtssq8jz/26/

I stumbled upon similar problem and see if this can help you:

 var $frag = new DocumentFragment(); var html = '' ; [].forEach.call($frag.children, function(el) { html += el.outerHTML; }); 

Basically iterate through the children property of document fragment and concatenate the outerHTMLs of its elements. :)

If f is a documentFragment, its innerHTML can be retrieved using:

console.log([].map.call(f.children, e => e.outerHTML).join('\n'));

Note that map is not a method of f.children . As a result, the following code doesn't work:

console.log(f.children.map(e => e.outerHTML).join('\n'));

I have come across this sort of problem previously, and I came to the conclusion that a document fragment is easier to work with when it has a single, top-level node. With that in mind, I would probably use a known 'container' element inside the document fragment, and then set and retrieve the innerHTML of that.

Something like this:

var fragment = document.createDocumentFragment(); //Initialise the fragment
fragment.appendChild(document.createElement('div')); //Create a top-level container element.
fragment.firstChild.innerHTML = 'Your chunk of DOM'; // Set the contents of your fragment, either with innerHTML, or by appending the child node.

console.log(fragment.firstChild.innerHTML); //Use any normal DOM node method to access the contents.

Basically you always use fragment.firstChild to access the contents of your fragment, so you have access to all of a DOM node's usual methods.

I find that element.childNodes have is forEach method

so we can use that for clean the experience a little

 var $frag = new DocumentFragment();
 var html = '' ; 
 $frag.childNodes.forEach( function(el) { 
   html += el.outerHTML;
 });

Or EC6 shorted

const innerHTML = [...$frag.childNodes].map( n=> n.outerHTML ).join('\n')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM