Search code examples
javascripthtmldomtext

How do I know if the content of a div contains another element HTML or just a text?


Example 1

there's only text without any HTML element:

<td class="txt">
some text
</td>

Example 2

there's a combination of text and HTML element:

<td class="txt">
some text with <span>Elment HTML</span>
</td>

Example 3

there's only HTML element:

<td class="txt">
<span>only HTML Element</span>
</td>

My try:

let txt = document.querySelector('.txt').innerHTML;
if(/<.*?>/.test(txt)){
    console.log('mixed text and tags!')
}else{
    console.log('only text!')
}

And How can I know the case where only tags without any text combined with.
And Is it the right way of doing that?


Solution

  • Loop though the child nodes and check if there are any non-text nodes.

    let children = Array.from(document.querySelector('.txt').childNodes);
    if (children.every(node => node.nodeType == Node.TEXT_NODE)) {
        console.log('only text');
    } else {
        console.log('mixed text and tags');
    }