tiger tiger - 7 months ago 13
Javascript Question

Placing text in the center of svg

I am creating an

<svg>
, and I want to put text in the center of the
<svg>
, when I click on the first button, the svg doesn't have text, when I click on the second button, the text show up. The first one I just add the position of svg. but I don't know why the text does not show up?

Thank you



$(document).ready(function() {
$('#testbtm').click(function() {
var str = '<svg class="hexagon" class="ui-widget-content" style="position:absolute; left:200; top:300;"\
<text fill="black" x=75 y=75 style="text-anchor: middle">1</text>\
<path d="M38 0 L113 0 L150 65 L113 130 L38 130 L0 65 Z" / fill="none" stroke="blue"></svg>'
var svgElement = $(str);
svgElement.children('text').text(1);
svgElement.attr("class", "hexagon ui-widget-content");
$("#display").append(svgElement);
}); //end click
$('#testbtm2').click(function() {
$('.hexagon').each(function() {
var svgElement = $('<svg class="hexagon" class="ui-widget-content">\
<text fill="black" x=75 y=75 style="text-anchor: middle">1</text>\
<path d="M38 0 L113 0 L150 65 L113 130 L38 130 L0 65 Z" / fill="none" stroke="blue"></svg>');
svgElement.children('text').text(1);
svgElement.attr("class", "hexagon ui-widget-content");
$("#display").append(svgElement);
});
}); // end click
}); // end ready

#display {
height: 500 px;
width: 500 px;
border: 1 px solid black;
overflow: auto;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="display"></div>
<button id="testbtm">test</button>
<button id="testbtm2">test2</button>




Answer

You are missing a closing bracket > on your opening svg tag.