Prashant Patel Prashant Patel - 3 months ago 16
Javascript Question

Count number of hashtags inside multiple divs

I've multiple

<p>
on my page. They do not have classes or ids.
What I'm trying to achieve is to be able to target every single of these
<p>
s count how many hashtags are in there and display the result inside the
<span>
.

structure example:

<div class="parent">
<p>
#test #test #test
</p>
<span></span>
</div>

<div class="parent">
<p>
#test #test #test
</p>
<span></span>
</div>

<div class="parent">
<p>
#test #test #test
</p>
<span></span>
</div>


this is working but it's counting everything:

$(function() {
var text = $(this).find("pre").text();
var hashTags = text.split("#").length;
var result = hashTags - 1;

$('#output').html('words count: ' + result);
});

Answer

You can try below code:

//loop through every element with class parent
$(".parent").each( function(index) {
  //get number of tags per in <p>
  var tags = $(this).find("p").text().split("#").length - 1;
  //write the number of tags in <span>
  $(this).find("span").text(tags);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
    <p>
        #test #test #test
    </p>
    <span></span>
</div>

<div class="parent">
    <p>
        #test #test #test
    </p>
    <span></span>
</div>

<div class="parent">
    <p>
        #test #test #test
    </p>
    <span></span>
</div>

Comments