2

When the title tag is appended dynamically with text, the title tag content is not showing dynamically in mouseover of the text, but if the same title tag is given in code (statically) it is working fine.

Can any one help me out here?

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>JSP Page</title>
  <script>
    function appendTitle() {
      try {
        var node = document.createElement("title");
        node.innerText = "I love SVG";
        document.getElementById("abcd").appendChild(node);
      } catch (e) {

      }
    }
  </script>
</head>

<body>
  <svg height="30" width="200">
        <text x="0" y="15" fill="red" id="abcd">

        I love SVG!
        </text>
        </svg>
  <button onclick="appendTitle()">click</button>
</body>
Robert Longson
  • 118,664
  • 26
  • 252
  • 242
affu
  • 141
  • 1
  • 8
  • write the same in question and update it with proper formatting so that others can help you out – Nagaraju Jan 27 '18 at 06:07
  • did u get my question..when u check the code? – affu Jan 27 '18 at 06:08
  • Looks like you'd need to refresh the entire SVG for this: `document.getElementById("abcd").innerHTML = document.getElementById("abcd").innerHTML;` – Nisarg Shah Jan 27 '18 at 06:21
  • Possible duplicate of [jquery's append not working with svg element?](https://stackoverflow.com/questions/3642035/jquerys-append-not-working-with-svg-element) – Nisarg Shah Jan 27 '18 at 06:21
  • The answers to linked question are about jQuery, but they apply just as well for plain JS. – Nisarg Shah Jan 27 '18 at 06:22

1 Answers1

0

There are a couple of problems here:

  1. SVG elements must be created in the SVG namespace with createElementNS, you've actually created a HTML title element.
  2. SVG elements don't support innerText, you want textContent. Even better textContent works on HTML elements too.

function appendTitle(){
    try{
        var node = document.createElementNS("http://www.w3.org/2000/svg", "title");
        node.textContent = "I love SVG";
                document.getElementById("abcd").appendChild(node); 
    }catch(e){

    }
}
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body>
    <svg height="30" width="200">
    <text x="0" y="15" fill="red" id="abcd">

    I love SVG!
    </text>
    </svg>
    <button onclick="appendTitle()">click</button>
</body>
Robert Longson
  • 118,664
  • 26
  • 252
  • 242