Kshitij Bhardwaj
Kshitij Bhardwaj

Reputation: 11

How do I find a specific element using css class but no ID using Jquery?

I have an html code as

<div class="container">
    <div class="ax" > <p>some text ... </p> </div>
    <div class="ax" > <p>some text ... </p> </div>
    <div class="ax" > <p>some text ... </p> </div>
    <div class="ax" > <p>some text ... </p> </div>
</div>

Now I need to check each specific "p" in the div classed "ax" if it has more than 175 characters, if it does, it need to show "read more" text in the end.

My main problem is that I can't use id's because these divs will be auto generated.

Please help.

Upvotes: 0

Views: 41

Answers (3)

Ghostff
Ghostff

Reputation: 1458

$('.ax').each(function() {
  if($(this).find('p').text().length > 175){
    //redmore();
  }
});

Upvotes: 0

adeneo
adeneo

Reputation: 318342

Get the text of each paragraph, check the length, and use a condition to return the "read more" text

$('.ax p').text(function(_, txt) {
   return txt.length > 175 ? txt.slice(0,175) + '... read more ...' : txt;
});

Upvotes: 1

Axel Amthor
Axel Amthor

Reputation: 11106

In order to access each of the `ax' elements, just do:

   $(".ax > p").each( function(index, elem) {
        // elem now is one of the "p" tags with "ax" class elements
        if ( $(elem).html().length > 175 ....

   });

the callback will be called for each of the elements found. See: http://api.jquery.com/each/

Upvotes: 0

Related Questions