Back to all resources
jQuery
typography

Fix Paragraph Runts With Nonbreaking Space

By Corey Moen
This JavaScript code snippet is designed to prevent runts in HTML text elements. A runt is a single word on the last line of a paragraph, which can be visually unappealing. The code targets all HTML elements with the class .no-runt and modifies their text content to ensure that the last line contains at least two words.

The code operates as follows:
  1. It selects all elements with the class .no-runt.
  2. For each selected element, it splits the text content into an array of words.
  3. If the element contains more than one word, it appends the last word to the second-to-last word, separated by a non-breaking space ( ). This effectively joins the last two words together, ensuring they will appear on the same line.
  4. It then removes the last word from the array (since it has already been appended to the previous word).
  5. Finally, it joins the modified array of words back into a single string and sets it as the new HTML content of the element.
This approach ensures that no selected text element ends with a single word on its last line, thus enhancing the typographic appearance of text-heavy web pages.