+ 2

Can't set attributes to svg figures

I need to create rectangle using document.createElemet() and add it to svg. My code adds rect, but without attributes, how to fix it? https://code.sololearn.com/WuSW8TwCps3r/?ref=app

30th Nov 2021, 7:55 AM
Ashas Yiksvorogom
Ashas Yiksvorogom - avatar
4 Answers
+ 2
It's simple : 1_SVG is XML so to create an svg element, you have to provide it the svg namespace like this : var ns = "http://www.w3.org/2000/svg"; var r = document.createElementNS(ns, "rect"); 2_XML doesn't support attributes object setting syntext except the style attribute, so you have two choice : r.style.width = "100px"; or r.setAttribute("width", 100); 3_I am making a serie of tutorials of things related to coding and SVG and XML are in the list, so just visit this page and comment what you want to learn and if you foolow me, I will be able to give you coding tricks everyday : https://code.sololearn.com/WIb425hnGqfl/?ref=app
30th Nov 2021, 11:18 AM
VCoder
VCoder - avatar
0
Thanks, i will try it
2nd Dec 2021, 9:40 AM
Ashas Yiksvorogom
Ashas Yiksvorogom - avatar
0
VCoder i tried, but rectangle is still invisible https://code.sololearn.com/WuSW8TwCps3r/?ref=app
2nd Dec 2021, 9:43 AM
Ashas Yiksvorogom
Ashas Yiksvorogom - avatar
0
You forgot to use createElementNS instead createElement
2nd Dec 2021, 2:29 PM
VCoder
VCoder - avatar