How to access the description of a svg element in js?

321 Views Asked by At

svg elements can have descriptions as described here

https://developer.mozilla.org/en-US/docs/Web/SVG/Element/desc

Assuming I got the handle of the circle via getElementById, how can I access the content of the <desc> tag?

Adding an id to the tag cannot be a solution given the SVG comes from an editor that allows me to add id's in the elements, but not to their descriptions.

PS. It's not relevant, but the idea is to add javascript code in the descriptor to be executed (via Eval) to update the owner element.

Thanks!

2

There are 2 best solutions below

0
On BEST ANSWER

assuming you've the circle then calling

let desc = circle.getElementsByTagName("desc");

will get you all the desc elements that are descentants of the circle element.

You can loop over those and do what you want with them. Note that you'll get a collection of desc elements so if there's only one element it will be the first and only element in that collection.

4
On

You can retrieve the content of tag <desc> with textContent.

I made an example for you with the ability to change the content of the <desc> tag through <textarea>, by pressing a button

The first console.log() displays the default content of the <desc> tag. All subsequent console.log() show modified content.

let desc = document.querySelector('desc');
let textarea = document.querySelector('textarea');
let button = document.querySelector('button');

console.log(desc.textContent.trim());

button.onclick = function() {
  desc.textContent = textarea.value;
  console.log(desc.textContent.trim());
}
<textarea></textarea>
<button>change desc</button>

<svg viewBox="0 0 10 10" xmlns="http://www.w3.org/2000/svg">
  <circle cx="5" cy="5" r="4">
    <desc>
      I'm a circle and that description is here to
      demonstrate how I can be described, but is it
      really necessary to describe a simple circle
      like me?
    </desc>
  </circle>
</svg>