I know I can use CSS :first-line
pseudo-elmenent to target and change style of the first line in any block of text (like in this demo: http://jsfiddle.net/6H8sy/). So the first line can be found and targeted.
I was wondering if there's any way to actually select that text to reuse. Something like $(':first-line')
(which doesn't work as it is).
Since you can't select the pseudo element itself, you could replicate the behavior of
:first-line
, to determine the text. I wrote a quick JS function, similar to the one @Kevin B suggests. The function initially determines the height of the element if there is only one line of text present. Afor
loop is then used to remove a word from the text node until the element's new height equals the initial height. The function then returns with thefirst-line
text.Example Here - the function is run onLoad, therefore if the window's width changes, the text obviously won't match
first-line
. You could easily fix this by running the function when the screen is resized.JavaScript function - no jQuery
I don't know if I'm re-inventing the wheel here, or not; but this does work. I'm not aware of any jQuery or built-in JS that is able to achieve this. Disregarding browser support, this should also work without any cross-browser styling inconsistencies. It seems to work with any types of padding/borders. (example)
I guess this Stackoverflow question is what you are looking for:
getting the first line of text in an element jquery