Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 234
ghi Avatar asked Dec 07 '25 21:12

ghi


1 Answers

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 ) )
like image 104
Supersharp Avatar answered Dec 09 '25 11:12

Supersharp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!