How to select nth line of text (CSS/JS)

Interesting. You can do something like that with JavaScript:

$(function(){ 
  var p = $('p'); 
  var words = p.text().split(' '); 
  var text=""; 
  $.each(words, function(i, w){
                   if($.trim(w)) text = text + '<span>' + w + '</span> ' }
        ); //each word 
  p.html(text); 
  $(window).resize(function(){ 

    var line = 0; 
    var prevTop = -15; 
    $('span', p).each(function(){ 
      var word = $(this); 
      var top = word.offset().top; 
      if(top!=prevTop){ 
        prevTop=top; 
        line++; 
      } 
      word.attr('class', 'line' + line); 
    });//each 

  });//resize 

  $(window).resize(); //first one
});

Basically, we wrap each word with a span, and add a class based on the position of the span, whenever the window resizes. I’m sure it can be done more efficiently, but it works as a proof of concept. Of course, for even/odd lines, you can simplify the code.

Edge cases: I didn’t test it where the class changes the size or width of the words. It may end up very wrong.

Here it is in action: https://jsbin.com/piwizateni/1/edit?html,css,js,output

Leave a Comment

tech