In html, I have a button element with no text. It has a child svg element with some paths and rectangles. It works fine:
I try to create this in javascript. The problem is, that the button is not visible. If I set some text to it with textContent
or innerHtml
, the button is visible with the text, but the svg is not there. How can I create this button in javascript? This is the code:
var myButton = document.createElement("button");
myButton.setAttribute("class", "my-button");
myButton.setAttribute("id", "foo");
var mySVG = document.createElement("svg");
mySVG.setAttribute("id", "my-svg");
mySVG.setAttribute("viewBox", "0 0 12.25 15.45");
var icon1 = document.createElement("g");
icon1.setAttribute("class", "g-element1");
icon1.setAttribute("id", "g1");
var iconPath = document.createElement("path");
iconPath.setAttribute("d", "M0,25L0,0l12.25,7.7L0,15.45z");
var icon2 = document.createElement("g");
icon2.setAttribute("class", "g-element2");
icon2.setAttribute("id", "g2");
var rect1 = document.createElement("rect");
rect1.setAttribute("x", "0");
rect1.setAttribute("y", "0");
rect1.setAttribute("width", "4.1");
rect1.setAttribute("height", "15.45");
var rect2 = document.createElement("rect");
rect2.setAttribute("x", "8.1");
rect2.setAttribute("y", "0");
rect2.setAttribute("width", "4.1");
rect2.setAttribute("height", "15.45");
icon1.appendChild(iconPath);
icon2.appendChild(rect1);
icon2.appendChild(rect2);
mySVG.appendChild(icon1);
mySVG.appendChild(icon2);
myButton.appendChild(mySVG);
document.getElementById('some-element').appendChild(myButton)
.my-button {
font-size: 14px;
height: 17px;
cursor: pointer;
margin-left: 5px;
&:hover, &:focus {
opacity: .8;
}
}
<div id="some-element">
<button class="my-button" id="foo">
<svg id="my-svg" viewBox="0 0 12.25 15.45">
<g class="g-element1" id="g1">
<path d="M0,25L0,0l12.25,7.7L0,15.45z"/>
</g>
<g class="g-element2" id="g2">
<rect x="0" y="0" width="4.1" height="15.45"/>
<rect x="8.1" y="0" width="4.1" height="15.45"/>
</g>
</svg>
</button>
</div>
Also when I create just the button in javascript and I set no text to it (and no svg either), the button is not visible.