Hide content after 3 paragraphs <p>

Working with an API that spills content in p tags ... but it's too long. Thinking about hiding them, reaching a limit of 400 characters, but this is not a good idea, since it is possible to cut through the HTML tag.

So, I'm trying to hide the rest of the content after three paragraphs and with the text "Details", which will display the rest of the content. How to do it?

+3
source share
3 answers
<div><p></p><p></p><p></p><p></p><p></p>
    <a href="#readMore" class="readMore">Read More</a>
</div>

If you have such a structure, you can

$('div p:nth-child(3)').nextAll('p').hide();

and

$('a.readMore').click(function(){
    $(this).siblings('p').show();
    return false;
})

resources: - . nextAll ()

+3
source

You can use :gt() selectorand then .hide()or .remove():

var $content = $("#content");
$content.find("p:gt(2)").hide();

, .children() .slice(3):

$content.children().slice(3).hide();

, :

var $content = $("#content");
var $hiddenText = $content.children().slice(3).hide();
if ($hiddenText.length) {       
    var $button = $("<a href='#'>Read More...</a>").click(function() {
        $hiddenText.show();
        $button.remove();
        return false;
    }).appendTo($content);
}

jsFiddle demo

+3

This is a slightly inverse approach, but to do something like this.

<style>
#con p{
  display:none;
}
</style>

<div id='con'>
  <p></p>
  <p></p>
  <p></p>
  <p></p>
</div>

Then jquery select the first three p-tags and set the display lock.

Alternatively, you can use

<style>
#con{
  overflow:auto;
  max-height:300px;
}
</style>

And you do not have to worry about it.

0
source

Source: https://habr.com/ru/post/1757766/


All Articles