I want to use javascript for word limit on <p> tags, using foreach loop. It works pretty well but only works on the first data, like this:
This is how my foreach seems like:
<?php foreach ($khotbah as $key): ?>
<article class="article-post mb70">
<div class="post-content">
<a href="#"><h2 class="post-title">{{$key->title}}</h2></a>
<ul class="post-meta list-inline">
<li class="list-inline-item">
<i class="fa fa-user-circle-o"></i> <a href="#">{{$key->author}}</a>
</li>
<li class="list-inline-item">
<i class="fa fa-calendar-o"></i> <a href="#"><?php $date_created = date_create($key->created_at); echo date_format($date_created,'d F Y H:i')?></a>
</li>
</ul>
<p>{{$key->description}}</p>
<a href="ringkasan-khotbah/{{$key->id}}" class="btn btn-outline-secondary">Read More</a>
</div>
</article><!--article-->
<?php endforeach; ?>
and this is what I'm doing in my javascript:
<script type="text/javascript">
function truncateText(selector, maxLength) {
var element = document.querySelector(selector),
truncated = element.innerText;
if (truncated.length > maxLength) {
truncated = truncated.substr(0,maxLength) + '...';
}
return truncated;
}
document.querySelector('p').innerText = truncateText('p', 107);
</script>
is it possible to use javascript on foreach loop? Should I put another method on my javascript so it can be used on foreach loop?

querySelectorwill match the first element, since you have multipleptags, check outquerySelectorAll