Is it possible to append a div inside an SVG element?
You can't append HTML to SVG (technically you can with foreignObject
, but it's a rabbit hole). Furthermore, visible elements in SVG can't be nested, so elements such as circle
, rect
, path
and such can't have children elements.
How to append a div inside svg with javascript
You need to use createElement('div')
– not createElementNS
, since its not an svg element.
const svg = document.querySelector("#svg");
const svgns = "http://www.w3.org/2000/svg";
let bg = document.createElementNS(svgns, 'rect');
bg.setAttribute('class', 'bg');
bg.setAttribute('id', 'bg');
bg.setAttribute('x',"0");
bg.setAttribute("y","0");
bg.setAttribute("width", "200");
bg.setAttribute("height", '200');
bg.setAttribute("fill","#0357D5");
svg.appendChild(bg);
let fo = document.createElementNS(svgns, 'foreignObject');
fo.setAttribute("x", "0");
fo.setAttribute("y", "0");
fo.setAttribute("width", "60");
fo.setAttribute("height", "50");
svg.appendChild(fo);
let _div = document.createElement('div');
_div.setAttribute("xmlns", 'http://www.w3.org/1999/xhtml');
_div.textContent = 'Thanks';
svg.appendChild(_div);
fo.appendChild(_div);
svg{
display:inline-block;
width:20em;
}
<svg id="svg" viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg">
</svg>
D3 - Adding div to svg is appended but not seen AnguarJs
Got It. I needed to add this:
svg.append('foreignObject')
.attr('x', 40)
.attr('y', 100)
.attr('width', 180)
.attr('height', 100)
.append("xhtml:body")
.attr("id","words")
.html('<div style="width: 160px;"><p>Old text old text old text old text old text old text<p></div>');
Thanks @balajisoundar
Full Code:
//module declaration var app = angular.module('myApp',[]);
//Controller declarationapp.controller('myCtrl',function($scope){
$scope.svgWidth = 500;//svg Width $scope.svgHeight = 300;//svg Height
//resetting svg height and width in current svg d3.select("svg").attr("width", $scope.svgWidth).attr("height", $scope.svgHeight);
//Setting up of our svg with proper calculations var svg = d3.select("svg");
svg.append('foreignObject') .attr('x', 40) .attr('y', 100) .attr('width', 180) .attr('height', 100) .append("xhtml:body") .attr("id","words") .html('<div style="width: 160px;"><p>Old text old text old text old text old text old text<p></div>');});
svg{ border:2px solid black;}.red{ width:50px; height:50px; background:red;}
<html><head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.12/angular.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.3.0/d3.min.js"></script></head> <body ng-app="myApp" ng-controller="myCtrl"> <svg></svg></body> </html>
Create SVG Element from String and append it to Div Element
I don't know how to make the method you've been trying work, but there's a much simpler way: put everything in innerHTML
and let the browser sort out the details.
<html>
<body>
<h2>Boolean Network</h2>
<button type="button" onclick="appendSVG('svgAnchor', svgStr)">Next</button>
<div id="svgAnchor" value="3">
</div>
<script>
var svgStr = '<svg width="100" height="100"><circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow"/>';
function appendSVG(id, xml_string){
var el = document.getElementById(id)
el.innerHTML = xml_string;
}
</script>
</body>
</html>
how to get an svg from one div element to another div element
You're mixing jQuery with vanilla JS and while that's not a bad thing, it can be confusing. It's good for readability (and best-practices) to use one or the other.
$('#div3 svg').each(
function(i) {
$('#slides').append(
$('<div>').append($(this))
.addClass('item')
.attr('id', `check${i+1}`))
})
This loops through the svg elements in #div3
, uses $.append()
as a wrapper for the part that creates a div element and inserts $(this)
(the svg) inside the new div. Outside of that wrapper, it applies the className and an id.
This moves the svg from it's original place into slides. If you wanted to copy it over to slides, you would make this small change:
...
$('<div>').append($(this).clone())
...
// and here's that in one line
$('#div3 svg').each(function(i) { $('#slides').append($('<div>').append($(this)).addClass('item').attr('id', `check${i+1}`))})
.item {
float: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div3">
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>
<svg height="140" width="500">
<ellipse cx="200" cy="80" rx="100" ry="50" style="fill:yellow;stroke:purple;stroke-width:2" />
</svg>
<svg width="400" height="110">
<rect width="300" height="100" style="fill:rgb(0,0,255);stroke-width:3;stroke:rgb(0,0,0)" />
</svg>
<svg height="100" width="500">
<ellipse cx="240" cy="50" rx="220" ry="30" style="fill:yellow" />
<ellipse cx="220" cy="50" rx="190" ry="20" style="fill:white" />
</svg>
</div>
<div id='slides'></div>
How to append SVGs to a div?
Finally found a solution for this with help of a friend.
All i needed to do was:
$http({ ... }).then(function callback(resp) { // request to node server
var svg = resp.data.file;
var container = document.createElement('div');
var parser = new DOMParser();
var doc = parser.parseFromString(svg, "image/svg+xml");
container.appendChild(doc.documentElement);
});
jquery's append not working with svg element?
When you pass a markup string into $
, it's parsed as HTML using the browser's innerHTML
property on a <div>
(or other suitable container for special cases like <tr>
). innerHTML
can't parse SVG or other non-HTML content, and even if it could it wouldn't be able to tell that <circle>
was supposed to be in the SVG namespace.
innerHTML
is not available on SVGElement—it is a property of HTMLElement only. Neither is there currently an innerSVG
property or other way(*) to parse content into an SVGElement. For this reason you should use DOM-style methods. jQuery doesn't give you easy access to the namespaced methods needed to create SVG elements. Really jQuery isn't designed for use with SVG at all and many operations may fail.
HTML5 promises to let you use <svg>
without an xmlns
inside a plain HTML (text/html
) document in the future. But this is just a parser hack(**), the SVG content will still be SVGElements in the SVG namespace, and not HTMLElements, so you'll not be able to use innerHTML
even though they look like part of an HTML document.
However, for today's browsers you must use XHTML (properly served as application/xhtml+xml
; save with the .xhtml file extension for local testing) to get SVG to work at all. (It kind of makes sense to anyway; SVG is a properly XML-based standard.) This means you'd have to escape the <
symbols inside your script block (or enclose in a CDATA section), and include the XHTML xmlns
declaration. example:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"><head>
</head><body>
<svg id="s" xmlns="http://www.w3.org/2000/svg"/>
<script type="text/javascript">
function makeSVG(tag, attrs) {
var el= document.createElementNS('http://www.w3.org/2000/svg', tag);
for (var k in attrs)
el.setAttribute(k, attrs[k]);
return el;
}
var circle= makeSVG('circle', {cx: 100, cy: 50, r:40, stroke: 'black', 'stroke-width': 2, fill: 'red'});
document.getElementById('s').appendChild(circle);
circle.onmousedown= function() {
alert('hello');
};
</script>
</body></html>
*: well, there's DOM Level 3 LS's parseWithContext, but browser support is very poor. Edit to add: however, whilst you can't inject markup into an SVGElement, you could inject a new SVGElement into an HTMLElement using innerHTML
, then transfer it to the desired target. It'll likely be a bit slower though:
<script type="text/javascript"><![CDATA[
function parseSVG(s) {
var div= document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
div.innerHTML= '<svg xmlns="http://www.w3.org/2000/svg">'+s+'</svg>';
var frag= document.createDocumentFragment();
while (div.firstChild.firstChild)
frag.appendChild(div.firstChild.firstChild);
return frag;
}
document.getElementById('s').appendChild(parseSVG(
'<circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red" onmousedown="alert(\'hello\');"/>'
));
]]></script>
**: I hate the way the authors of HTML5 seem to be scared of XML and determined to shoehorn XML-based features into the crufty mess that is HTML. XHTML solved these problems years ago.
Related Topics
Why Does Settimeout() "Break" for Large Millisecond Delay Values
Differences Between JavaScript Regexp Literal and Constructor
Window.Open and Pass Parameters by Post Method
How to Append a Div Inside an Svg Element
Closing Websocket Correctly (Html5, JavaScript)
How to Tell If a Browser Supports <Input Type='Date'>
Decode HTML Entities in JavaScript
How to Clear a Chart from a Canvas So That Hover Events Cannot Be Triggered
Make Checkbox Behave Like Radio Buttons with JavaScript
JavaScript Sort Function. Sort by First Then by Second
Foreach on Array of Undefined Created by Array Constructor
Nesting Quotes in JavaScript/Html
CSS Delivery Optimization: How to Defer CSS Loading
HTML "Data-" Attribute as JavaScript Parameter
How to Change Active Class While Click to Another Link in Bootstrap Use Jquery