Search code examples
javascripthtmltags

Is there any way to check if text is inside html tag?


Let suppose I need to extract every text from specific html tag:

HTML:

<div id="container">
<div id="subject">

<span><a></a></span>

</div>
</div>

var subject = document.getElementById('subject').innerHTML;
console.log(subject); // <span><a></a></span>

So we don’t have any text inside, but if there is - how to check if there is text outside of <> tags inside our specific html element?

fiddle for better visualization - http://jsfiddle.net/kxarc6o3/


Solution

  • The best way is to go for innerText, innertHTML gives you the entire content within the tag including the html tags it holds and the html its child or decendents holds. innerText always gives you the text it contains(only the element not its decendents).

    in your example

    <span id ='spanid'>hello<a>hi</a></span>
    

    document.getElementbyID('spanid').innerText will only give hello, as a string

    whereas document.getElementbyID('spanid').innerHTML will give the entire hmtl contains it has inside it (here hello<a>hi</a> ) in a string format.

    To get innerText of all possible elements inside the span tag you need to use recursion, there is no other way as we dont know how many children or decedents it has.

    printInnerText(ele){
     if(ele.childNodes.length >= 1){
        children = ele.childNodes;
        for(var i=0;i<children.length;i++)
         printInnerText(children[i])
     }else{
        console.log(ele.innerText);
     }
    }