javascripttexttextnode

How to detect that a text node is inside a tag


I have html file

    <div>1. <span id="el1"> hello </span> world</div>

    <div>

      <span id="el2"> first part</span>
      <span id="el3"> second part </span><br />

    </div>

I have "hello" text node

document.querySelector("#el1").childNodes[0] // hello
document.querySelector("#el2").childNodes[0].splitText(6) // split text node ("first" and "part")

how can I check if text node is wrapped by any tag.
I can also have text node "part" in <span>first part </span> (so there can be two text nodes "first" and "part") result of js splitText method.
How to cover all edge cases?
I tried this to compare it

document.querySelector("#el1").textContent.trim() === document.querySelector("#el1").childNodes[0].nodeValue.trim()

I expect to get boolean value true or false when comparing it.


Solution

  • If indeed so, all you need is to check if the text node parent has only 1 child.

    function isTextWrapped(textnode) {
      return textnode.parentElement.childNodes.length === 1
    }
    
    
    
    var el1Text = document.querySelector("#el1").childNodes[0] // hello
    var el2Text = document.querySelector("#el2").childNodes[0].splitText(6) // split text node ("first" and "part")
    
    console.log(isTextWrapped(el1Text))
    console.log(isTextWrapped(el2Text))
    <div>1. <span id="el1"> hello </span> world</div>
    
    <div>
    
      <span id="el2"> first part</span>
      <span id="el3"> second part </span><br />
    
    </div>