'How to add different tooltips using title for <line/> in svg

I am working with a svg element and I want to assign different title to different svg <line>. For example

<!DOCTYPE html>
<html>
   <body>
      <link rel="stylesheet" href="style.css">
      </link>
      <svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 720">
         <line class="upper clone" x1="10" y1="0" x2="220" y2="0" style="stroke:rgb(110, 31, 194);stroke-width:1" />
         <title>original upper location (10,0)</title>
         <line class="lower clone" x1="10" y1="260" x2="220" y2="260" style="stroke:rgb(218, 149, 22);stroke-width:1" />
         <title>original lower location (10,260)</title>
         <rect x="40" y="50" width="80" height="100" fill="#007bbf">
            <title>A blue box</title>
         </rect>
         <rect x="180" y="50" width="80" height="100" fill="#ec008c">
            <title>A pink box</title>
         </rect>
      </svg>
      <!--<script src="index.js"></script>-->
      <script src="index2.js"></script>
   </body>
</html>

As you can see, it only shows the same tooltip for both the lines, whereas it is different for rects.



Solution 1:[1]

You insert the <title> element inside the two <line> elements like how a <div> works:

<!DOCTYPE html>
<html>
   <body>
      <link rel="stylesheet" href="style.css">
      </link>
      <svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 720">
         <line class="upper clone" x1="10" y1="0" x2="220" y2="0" style="stroke:rgb(110, 31, 194);stroke-width:1">
           <title>original upper location (10,0)</title>
         </line>
         <line class="lower clone" x1="10" y1="260" x2="220" y2="260" style="stroke:rgb(218, 149, 22);stroke-width:1">
           <title>original lower location (10,260)</title>
         </line>
         <rect x="40" y="50" width="80" height="100" fill="#007bbf">
            <title>A blue box</title>
         </rect>
         <rect x="180" y="50" width="80" height="100" fill="#ec008c">
            <title>A pink box</title>
         </rect>
      </svg>
      <!--<script src="index.js"></script>-->
      <script src="index2.js"></script>
   </body>
</html>

A simple but effective solution.

Note: You may want to get the cursor to just the right position to see the tooltips.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mrwolferinc