Categories
JavaScript Answers

How to add text to SVG document in JavaScript?

Spread the love

Sometimes, we want to add text to SVG document in JavaScript.

In this article, we’ll look at how to add text to SVG document in JavaScript.

How to add text to SVG document in JavaScript?

To add text to SVG document in JavaScript, we can use various DOM manipulation methods.

For instance, we write:

<svg xmlns="https://www.w3.org/2000/svg" xmlns:xlink="https://www.w3.org/1999/xlink" width="300" height="300">
  <g>
  </g>
</svg>

to add an svg element.

Then we write:

const svgNS = "http://www.w3.org/2000/svg";
const newText = document.createElementNS(svgNS, "text");
newText.setAttributeNS(null, "x", 10);
newText.setAttributeNS(null, "y", 30);
newText.setAttributeNS(null, "font-size", "20px");

const textNode = document.createTextNode('hello world');
newText.appendChild(textNode);
document.querySelector("g").appendChild(newText);

to call createElementNS to create the textelement with thesvgNS` namespace.

Then we can setAttributeNS to set attributes on the text element.

Next, we call createTextNode to create a text node with 'hello world' as the text content.

Then we call appendChild with textNode to append the text node to the text element.

Finally, we select the g element with querySelector and call appendChild with the newText text node to append it as the child of g.

Conclusion

To add text to SVG document in JavaScript, we can use various DOM manipulation methods.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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