Home > Back-end >  How do I know if the content of a div contains another element HTML or just a text?
How do I know if the content of a div contains another element HTML or just a text?

Time:09-20

Example 1

there's only text without any HTML element:

<td >
some text
</td>

Example 2

there's a combination of text and HTML element:

<td >
some text with <span>Elment HTML</span>
</td>

Example 3

there's only HTML element:

<td >
<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?

CodePudding user response:

    const div = document.querySelector('.txt');
if(div.innerText === div.innerHTML){
  console.log('only text!')
}else{
    console.log('mixed text and tags!')
}

CodePudding user response:

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');
}

CodePudding user response:

What you might look for is https://developer.mozilla.org/en-US/docs/Web/API/Element/children The children collection only contains nodes but ignores text:

if (document.querySelector('.txt').children.length > 0) {
  console.log('at least one node, possibly mixed with text')
} else {
  console.log('no tags (might be only text or empty)')
}

CodePudding user response:

You can use the firstElementChild property of your element. If it's null, there are no child elements.

let element = document.querySelector('.txt');
if (element.firstElementChild){
    console.log('mixed text and tags!')
}else{
    console.log('only text!')
}
  • Related