Automatically add line breaks in SVG text

Add line breaks in SVG text with jQuery, based on a separator. In the example below the separator is plain text <br>.

<div class="svg-container">
  <svg version="1.1" xmlns="" xmlns:xlink="">
      <tspan x="0" y="0" style="font-family: Helvetica; font-size: 8px;">Lorem ipsum <br> dolor sit amet</tspan>
$('.svg-container').each(function() {
  // line breaks
  $(this).find('text').each(function() {
    if (/<br>/i.test($(this).text())) {
      var tspan = $(this).find('tspan:first-child');
      var tspanX = tspan.attr('x');
      var tspanY = tspan.attr('y');
      var tspanStyle = tspan.attr('style');
      var lines = $(this).text().split('<br>');
      var lineHeight = parseFloat(tspan.css('fontSize'));
      for (var i = 0; i < lines.length; ++i) {
        $(this).append('<tspan x="'+ tspanX +'" y="'+ (parseFloat(tspanY) + (lineHeight * i)) +'" style="'+ tspanStyle +'">'+ $.trim(lines[i]) +'</tspan>');

  // refresh svg


  1. written by: Roger on April 29, 2024 at 5:00 pm - Reply

    stupid idea to manipulate SVG element by script

Leave a Reply

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

+ 63 = 69

This site uses Akismet to reduce spam. Learn how your comment data is processed.