Home > Blockchain >  Count number of words inside a div - ignoring those inside a specified child div
Count number of words inside a div - ignoring those inside a specified child div

Time:03-25

I am looking to count the number of words inside a specified div. The specified div - has a child div included with the class ignoreMe - I have a nice bit of code working well to count the words in the parent div INCLUDING the contents of the ignoreMe div... what I cant see to get working is to get the code to ignore the content in the ignoreMe div... any tips on how to achieve this?

function countWordsInDiv () {
var txt = $(".parentDIV").text();
wordCount = txt.replace( /[^\w ]/g, "" ).split( /\s / ).length;
console.log(wordCount)
}
$(window).load(function() { countWordsInDiv(); });

CodePudding user response:

You could subtract the amount of words from the element you need to ignore.

function countWordsInDiv () {
  console.log(returnWords($(".parentDIV").text()) - returnWords($(".ignoreMe").text()))
}

function returnWords(str) {
  return str.replace( /[^\w ]/g, "" ).split( /\s / ).length;
}

countWordsInDiv();

$('#total').text(returnWords($(".parentDIV").text()));
$('#total_to_ignore').text(returnWords($(".ignoreMe").text()));
$('#total_without_ignore').text(returnWords($(".parentDIV").text()) - returnWords($(".ignoreMe").text()));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div>Total: <span id="total"></span></div>
<div>Total Ignore: <span id="total_to_ignore"></span></div>
<div>Total Without Ignore: <span id="total_without_ignore"></span></div>
<br><br>

<div >
  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Omnis molestiae quasi nobis modi minima cupiditate vel totam, rem in, cumque, beatae quod doloribus, minus tenetur libero. Ex possimus, accusamus doloremque.
  <div >Lorem ipsum dolor sit amet, consectetur adipisicing elit. Soluta totam veritatis eum, illo impedit? Quo consequuntur deserunt unde quam cumque quae quibusdam debitis pariatur, natus aperiam maiores eaque, quod mollitia?</div>
  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptates ea odio esse architecto exercitationem doloribus eos nulla tempore adipisci. Accusamus reiciendis beatae excepturi placeat laborum mollitia eos dolores quod. Laboriosam!
</div>

  • Related