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,

Related


querySelectorAll doesn't work?

I stock up on tea Here is my javascript code: function answer(){ var list = document.querySelectorAll("#fish"); list[1].onclick = talk(); } function talk(){ alert('hello!'); } window.onload = answer(); When running, it pops up a browser window with a warnin

querySelectorAll doesn't work

username I have a requirement where I have .divto pick the last container in the container and apply some business logic to it. The selection of the last option .divmust be dynamic, as the user can choose to add/remove .divelements. I tried it initially, query

a:active doesn't work, is there any other code?

username Not sure if this is the CSS I'm looking for. I want active links to have hover color. Active links are sidelinks that I'm currently visiting. .widget-area .widget a { color: #bc7ed1; } .widget-area .widget a:hover { color: #D6A0DB; } .widget-a

a:active doesn't work, is there any other code?

username Not sure if this is the CSS I'm looking for. I want active links to have hover color. Active links are sidelinks that I'm currently visiting. .widget-area .widget a { color: #bc7ed1; } .widget-area .widget a:hover { color: #D6A0DB; } .widget-a

The method that returns the icon doesn't work

username I have a method that takes strings and integers as parameters. This method basically returns a smaller cropped portion of the original image. The strings are the paths and integers that I use for the specific parts I need in the switch statement, I've

Method overloading doesn't work with other parameters

user1236048: Why is this not allowed and treated as the same signature? public Object myMethod(Map<String, String[]> values) { return this; } public Object myMethod(Map<String, String> values) { return this; } Duncan Jones: The answer to the urban myth

If other doesn't work in the class's Method

Deepak After asking the question, the code terminates at line 11. It will run the if statement. The program doesn't give any errors either. class Car(): def __init__ (self, name): print (f"Hello and welcome {name}. You have won a Ferrari. Please e

ActionPerformed method doesn't work for other classes

because of Caracas I am trying to add an object of class RedSquare to a JFrame of class CatchMeV2. What's the question? public class CatchMeV2 implements ActionListener{ int width = 400; int height = 450; public static void main(String[] args) { JFrame fr

ActionPerformed method doesn't work for other classes

because of Caracas I am trying to add an object of class RedSquare to a JFrame of class CatchMeV2. What's the question? public class CatchMeV2 implements ActionListener{ int width = 400; int height = 450; public static void main(String[] args) { JFrame fr

Method overloading doesn't work with other parameters

user1236048: Why is this not allowed and treated as the same signature? public Object myMethod(Map<String, String[]> values) { return this; } public Object myMethod(Map<String, String> values) { return this; } Duncan Jones: The answer to the urban myth

If other doesn't work in the class's Method

Deepak After asking the question, the code terminates at line 11. It will run the if statement. The program doesn't give any errors either. class Car(): def __init__ (self, name): print (f"Hello and welcome {name}. You have won a Ferrari. Please e

ActionPerformed method doesn't work for other classes

because of Caracas I am trying to add an object of class RedSquare to a JFrame of class CatchMeV2. What's the question? public class CatchMeV2 implements ActionListener{ int width = 400; int height = 450; public static void main(String[] args) { JFrame fr

Union step doesn't work with multiple elements

Ferm The following query returns a user map with an "injected" property called "issues" that works fine when g.V().has()returning a single user , but not when returning multiple users: return g.V().has("user", "userId", 1) .union( __.valueMap(

Union step doesn't work with multiple elements

Ferm The following query returns a user map with an "injected" property called "issues" that works fine when g.V().has()returning a single user , but not when returning multiple users: return g.V().has("user", "userId", 1) .union( __.valueMap(

Union step doesn't work with multiple elements

Ferm The following query returns a user map with an "injected" property called "issues" that works fine when g.V().has()returning a single user , but not when returning multiple users: return g.V().has("user", "userId", 1) .union( __.valueMap(

Selecting multiple elements in jQuery doesn't work

moonlight Currently, I have this jQuery code: jQuery("#slideshow article").removeClass("current").removeAttr("class").eq(idx).addClass("current"); jQuery("#slideshow nav a").removeClass("current").removeAttr("class").eq(idx).addClass("current"); As you can se

Union step doesn't work with multiple elements

Ferm The following query returns a user map with an "injected" property called "issues" that works fine when g.V().has()returning a single user , but not when returning multiple users: return g.V().has("user", "userId", 1) .union( __.valueMap(

Union step doesn't work with multiple elements

Ferm The following query returns a user map with an "injected" property called "issues" that works fine when g.V().has()returning a single user , but not when returning multiple users: return g.V().has("user", "userId", 1) .union( __.valueMap(

Union step doesn't work with multiple elements

Ferm The following query returns a user map with an "injected" property called "issues" that works fine when g.V().has()returning a single user , but not when returning multiple users: return g.V().has("user", "userId", 1) .union( __.valueMap(

Union step doesn't work with multiple elements

Ferm The following query returns a user map with an "injected" property called "issues" that works fine when g.V().has()returning a single user , but not when returning multiple users: return g.V().has("user", "userId", 1) .union( __.valueMap(

Selecting multiple elements in jQuery doesn't work

moonlight Currently, I have this jQuery code: jQuery("#slideshow article").removeClass("current").removeAttr("class").eq(idx).addClass("current"); jQuery("#slideshow nav a").removeClass("current").removeAttr("class").eq(idx).addClass("current"); As you can se

POST method doesn't work but doesn't show any error

Kotlin I am new to PHP. I'm using the below code in my project and it doesn't work, but no errors are thrown. I tried to convert it to GET method but it still doesn't work. PHP is my frontend and MYSQL database is my backend. I have created the table in the ba