How to access SVG elements with Javascript
Is it possible to do it this way, as opposed to using something like Raphael or jQuery SVG?
Definitely.
If it is possible, what's the technique?
This annotated code snippet works:
<!DOCTYPE html>
<html>
<head>
<title>SVG Illustrator Test</title>
</head>
<body>
<object data="alpha.svg" type="image/svg+xml"
id="alphasvg" width="100%" height="100%"></object>
<script>
var a = document.getElementById("alphasvg");
// It's important to add an load event listener to the object,
// as it will load the svg doc asynchronously
a.addEventListener("load",function(){
// get the inner DOM of alpha.svg
var svgDoc = a.contentDocument;
// get the inner element by id
var delta = svgDoc.getElementById("delta");
// add behaviour
delta.addEventListener("mousedown",function(){
alert('hello world!')
}, false);
}, false);
</script>
</body>
</html>
Note that a limitation of this technique is that it is restricted by the same-origin policy, so alpha.svg
must be hosted on the same domain as the .html
file, otherwise the inner DOM of the object will be inaccessible.
Important thing to run this HTML, you need host HTML file to web server like IIS, Tomcat
SVG + Javascript : how can I access elements using classes?
You could just select the elements with the correct class in the first place:
var polygons = document.querySelectorAll("polygon.red");
alert("There are " + polygons.length + " red shapes")
Updated Fiddle
An alternative would be to use classList
:
var polygons = document.getElementsByTagName("polygon");
var j = 0;
for (i = 0; i < polygons.length; i++) {
console.log( polygons[i].className );
if (polygons[i].classList.contains( "red" ) ) {
j++;
}
};
alert("There are " + j + " red shapes")
Another Fiddle
Your code fails, because className
does not return a string, but an SVGAnimatedString
, which obviously is not equal to your "red"
.
Trying to access SVG elements generated with use with JavaScript
SVG use elements are like shadow DOM elements in HTML. Only the attributes of the USE element itself is exposed via the SVG DOM - you cannot alter any properties on a single USE element instance that are being cloned from the original symbol. It's not like a macro.
How to access the description of a svg element in js?
assuming you've the circle then calling
let desc = circle.getElementsByTagName("desc");
will get you all the desc elements that are descentants of the circle element.
You can loop over those and do what you want with them. Note that you'll get a collection of desc elements so if there's only one element it will be the first and only element in that collection.
Access an element by class name from SVG using JavaScript
Your javascript function gets called right after loading the window. At that time, the svg picture has not been loaded, and its inner elements do not exist. According to this answer, you might find the elements by changing the script to:
const el = document.getElementById('container2');
el.addEventListener("load", () => {
console.log(document.getElementsByClassName('ads'));
});
The script should be called after loading #container2
. You can just add the script after the html code or run the script after loading the page.
How do I select an SVG inside an `object` tag?
You need to access the <object>
contentDocument
in order to access its contained elements.
To do this, you also need to wait until your <object>
has loaded its content.
I'm not too much into d3, so it might not be the best d3 way of doing, but at least it works:
(but not in StackSnippet's null origined iframes...)
fetch('https://upload.wikimedia.org/wikipedia/commons/f/fd/Ghostscript_Tiger.svg')
.then(r => r.blob())
.then(b => obj.data = URL.createObjectURL(b));
obj.onload = function() { // wait for the svg has loaded
var tooltip = d3.select("body")
.append("div")
.style("position", "absolute")
.style("z-index", "10")
.style("visibility", "hidden")
.text("Hello");
var obj = this; // we're in the object's load event handler.
var svg = d3.select(obj.contentDocument) // get the contentDocument
.select("svg"); // then get the svg inside
svg.selectAll('g')
.on("mouseover", function() {
return tooltip.style("visibility", "visible");
})
.on("mousemove", function() {
var event = d3.event;
var offset = 20;
var topPosition = (event.pageY - offset) + "px";
var leftPosition = (event.pageX + offset) + "px";
return tooltip.style("top", topPosition).style("left", leftPosition);
})
.on("mouseout", function() {
return tooltip.style("visibility", "hidden");
});
};
<script src="https://d3js.org/d3.v4.min.js"></script>
<object id="obj" type="image/svg+xml"></object>
Fiddle
JavaScript accessing inner DOM of SVG
You need to wait until the SVG is loaded and than you can access the contentDocument:
var mySVG = document.getElementById("SVG");
var svgDoc;
mySVG.addEventListener("load",function() {
svgDoc = mySVG.contentDocument;
alert("SVG contentDocument Loaded!");
}, false);
Related Topics
How to Access Iframe Elements with JavaScript
Differencebetween String Primitives and String Objects in JavaScript
How to Loop Through an Array Containing Objects and Access Their Properties
How to Download a File with Angular2 or Greater
How to Iterate Through Table Rows and Cells in JavaScript
Defining Methods via Prototype VS Using This in the Constructor - Really a Performance Difference
Format Numbers in JavaScript Similar to C#
How to Quickly and Conveniently Disable All Console.Log Statements in My Code
Why Is [1,2] + [3,4] = "1,23,4" in JavaScript
Js Client-Side Exif Orientation: Rotate and Mirror Jpeg Images
Why Doesn't Equality Check Work with Arrays
Primitive Value VS Reference Value
How to Use Namespaces with Typescript External Modules
Concrete JavaScript Regular Expression for Accented Characters (Diacritics)
JavaScript Regex Multiline Text Between Two Tags
Javascript: How to Join/Combine Two Arrays to Concatenate into One Array
What Is the Stability of the Array.Sort() Method in Different Browsers