based on this: https://dev.to/gavinsykes/appending-a-child-to-an-svg-using-pure-javascript-1h9g
I was trying to append a filter inside the defs part of an SVG... But it didn't work. It gave me an error when i tried : Oo_banner.defs.appendChild(filter) Oo_banner being the id of the SVG.
So I plowed on thinking I could define my blur filter at the end of the SVG but even that doesn't work because it puts the feGaussianBlur after the filter tag. Anyway here's my code:
<svg id="Oo_banner" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 600 300">
<defs>
</defs>
<rect id="subj" x="30" y="30" width="70" height="70" fill="#f9f"/>
</svg>
<script>
var Oo_banner = document.querySelector("#Oo_banner"),
subj=document.querySelector("#subj"),
filter = document.createElementNS('http://www.w3.org/2000/svg','filter');
filter.setAttribute('id','blur_subj');
Oo_banner.appendChild(filter);
var filterBlur = document.createElementNS('http://www.w3.org/2000/svg','feGaussianBlur');
filterBlur.setAttribute('id','blur_subj_');
filterBlur.setAttribute('stdDeviation','15');
Oo_banner.appendChild(filterBlur);
subj.setAttribute('filter','url(#blur_subj)');
</script>
I also made a playpen here: https://codepen.io/trufo/pen/dyWbOQp
and here's the structure I get when I inspect the page in Chrome: https://i.sstatic.net/ZuXu3.png
so I have three questions:
1.) How to append a tag (filter) in the defs part of an SVG?
2.) How to append a tag (feGaussianBlur) inside the just created tag?
3.) How to make that last tag (feGaussianBlur) without a closing tag (like an img tag for example)
Thanks
You're getting your attributes and your DOM id's confused I think. If you want to append a child element to defs, then get a DOM reference to the defs element - which you can do by just moving that id down from the SVG to the defs.
Then, if you want to nest the feGaussianBlur inside the filter, append it to the filter DOM element - NOT the svg element.
(Also - I'd encourage better naming - having two different ID's distinguished by a trailing underscore is going to get you in trouble.)
const Oo_banner = document.querySelector("#Oo_banner");
let subj = document.querySelector("#subj");
filter = document.createElementNS('http://www.w3.org/2000/svg','filter');
filter.setAttribute('id','blurme');
Oo_banner.appendChild(filter);
let filterBlur = document.createElementNS('http://www.w3.org/2000/svg','feGaussianBlur');
filterBlur.setAttribute('id','blur_subj_');
filterBlur.setAttribute('stdDeviation','2');
filter.appendChild(filterBlur);
subj.setAttribute('filter','url(#blurme)');
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 600 300">
<defs id="Oo_banner">
</defs>
<rect id="subj" x="30" y="30" width="70" height="70" fill="green"/>
</svg>