Search code examples
javascriptdomdocumentfragment

Check if DocumentFragment is a normal Node


I've believed that my problem is pretty simple but after spending some time searching I cannot find a satisfactory solution.

I have a DocumentFragment element and I want to check if it's wrapped entirely by some html tag. Here is pseudo code which I'm trying to turn into JavaScript:

entireTagSelected = function (selRange) {
  var documentFragment = selRange.cloneContents();
  if (documentFragment is wrapped entirely by something) {
    return something;
  }
  return undefined;
}

For DocumentFragment like:

<span>Te<b>s</b>t</span>

the function should return span object.

But for fragments like:

Some text<span>Test</span>

it should return undefined.


Solution

  • You can get the children of the documentFragment, and if the length is 1 and its nodeType == 1 then it is a single element.

    function entireTagSelected (selRange) {
      var documentFragment = selRange.content
      var children = documentFragment.childNodes
      if ( children.length == 1 && children[0].nodeType == 1 ) 
        return children[0]
    }
    
    
    var template1 = document.createElement( 'template' )
    template1.innerHTML = "<span>Te<b>s</b>t</span>"
    
    var template2 = document.createElement( 'template' )
    template2.innerHTML = "Some text<span>Test</span>"
    
    var template3 = document.createElement( 'template' )
    template3.innerHTML = "Only text"
    
    console.log( entireTagSelected( template1 ) )
    console.log( entireTagSelected( template2 ) )
    console.log( entireTagSelected( template3 ) )