0

I want to count the total element and text inside the p tag

<p class="parent">
  <span class="child">Span Text</span> 
  Text Text Text
</p>

it is possible?

$(p).children(').length

I'm using this code and this giving me 1 only but I want count 2.

3 Answers3

1

You are looking for child nodes, and not children (read more about the difference here).

However, note that the actual number of child nodes in your HTML code would be 3, since there's a text node that holds the spaces before the span.

In this example, you can see the count of child nodes with or without the space before the span.

const parent1ChildNodes = document.querySelector('.parent1').childNodes.length
const parent2ChildNodes = document.querySelector('.parent2').childNodes.length

console.log(parent1ChildNodes)
console.log(parent2ChildNodes)
<p class="parent1">
  <span class="child">Span Text</span> 
  Text Text Text
</p>

<p class="parent2"><span class="child">Span Text</span> 
  Text Text Text
</p>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

children method only returns valid objects. "Text Text Text" is not an html object. Therefore it doesn't count. If you place it in another span, the length of the children becomes 2.

<p class="parent">
  <span class="child">Span Text</span> 
  <span>Text Text Text</span>
</p>
salix
  • 846
  • 6
  • 13
0

You need to use contents instead of children to get text nodes counted. Note that contents will also count comment nodes.

$(p).contents().length
Radu Diță
  • 13,476
  • 2
  • 30
  • 34