Solution 1 :

You are not counting the length of array returned when you split the text of the divs. Change your code to this.

$('.intro_text').each(function() {
  var lines = $(this).find("div").text().split("n").length;  
  var maxLine = 5;

  if(lines >= maxLine){
    $(this).after("<button>toggle</button>");
  }
});

Problem :

I’m trying to count the number of lines in a string for each div. But I would also like to set a maximum number and if the string inside a div is equal/greater to that number to show a button.

Here’s a codepen

jQuery:

$('.intro_text').each(function() {
   var lines = $(this).find("div").val().split("n");  
   var maxLine = 5;
   if(lines > maxLine){
      $(this).after("<button>toggle</button>");
   }
 });

Comments

Comment posted by Grumpy

Use .html() instead of val(), a div doesnt have a val

Comment posted by Shanice Morgan

Thanks. I had read up on length before but I thought it was the wrong property to use

Comment posted by Qonvex620

glad to help you, happy coding 🙂

By

Leave a Reply

Your email address will not be published. Required fields are marked *