querySelectorAll or any other method that returns multiple elements - doesn't work
Simon Vino
I want to get some posts written by a user in php and write a function in javascript that should cut the post after the 50th character and add three dots (...). Everything works fine if I use querySelector() or getElementById(), but I can't get it to work with any multi-element selection methods like querySelectorAll() or getElementsByClassName(). There are some posts on the page and I need to select them all.
Here is the HTML for PHP:
<?php while ($post = mysqli_fetch_assoc($result_posts)) : ?>
<div class="card p-0 m-0 mt-3">
<div class="card-header text-white">
<span>
<?= $post['title'] ?>
</span>
</div>
<div class="card-body">
<p class='article'>
<?= $post['article'] ?>
</p>
</div>
</div>
<?php endwhile ?>
rendered HTML
<div class="card-header text-white">
<span>Title </span>
</div>
<div class="card-body">
<p class="text-left article" id="article">
Article</p>
</div>
JS function:
function cutLongString() {
var article = document.querySelector('.article').textContent
if (article.length > 50) {
document.querySelector('p').innerHTML = article.slice(0, 49) + '...';
} else {
console.log(article)
}
}
cutLongString()
Like I said it works, but if I change the querySelector to the multi-element selection method it says "article is not defined".
Miroslav Glamuzina
You will have to loop through all the elements and set the new values textContent
one by one:
function cutLongString() {
const articles = document.querySelectorAll('.article')
Array.from(articles).forEach(a => {
if (a.textContent.length > 50) {
a.textContent = a.textContent.slice(0, 49);
}
})
}
cutLongString();
<div class="card p-0 m-0 mt-3">
<div class="card-header text-white">
<span>Title </span>
</div>
<div class="card-body">
<!--Dont assign multiple elements to the same ID. Remove the id="article" below from the <p/>-->
<p class="text-left article" id="article">Article</p>
</div>
</div>
<div class="card p-0 m-0 mt-3">
<div class="card-header text-white">
<span>Title </span>
</div>
<div class="card-body">
<p class="text-left article" id="article">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris</p>
</div>
</div>
Hope this helps,