Note that there are some explanatory texts on larger screens.

plurals
  1. POCan't add events to inline SVG elements
    primarykey
    data
    text
    <p>I'm trying to access inline SVG elements in JavaScript, to add a click event. I'm running into issues adding the event to anything else than a single element identified with id. Using document.getElementById("p1_1_1") will work, but I'll need to manipulate 200 rectangles, so I will need to use document.getElementsByTagName or document.getElementsByClassName - both of which return meaningful HTMLCollections, but the addEvent won't add the event.</p> <p>I've tried Firefox 17 and Chrome 23, and some additional methods, such as the <code>getElementsByTagNameNS</code>, bu no luck so far. </p> <p>Thankful for any help you can offer.</p> <p>Here are stripped down versions of the JS code and HTML/SVG I'm working with:</p> <p><strong>JavaScript:</strong></p> <pre><code> function testing() { var testDiv = document.getElementById("tester"); testDiv.innerHTML = '&lt;h1&gt;Success!&lt;/h1&gt;&lt;br&gt;'; } function addEvent(obj, evt, func) { if (obj.addEventListener) { obj.addEventListener(evt, func, false) } else if (obj.attachEvent) { obj.attachEvent("on" + evt, func); } else { alert("no success adding event"); } } function init() { var targetSquares = document.getElementsByTagName("rect"); addEvent(targetSquares, "click", testing); } window.addEvent(window, "load", init); </code></pre> <p><strong>inline SVG</strong></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en-GB"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;script type="text/javascript" src="bsroyale.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="tester"&gt; &lt;/div&gt; &lt;div id="gamemap"&gt; &lt;svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 600 600"&gt; &lt;rect x="50" y="50" width="20" height="20" class="p1" id="p1_1_1" /&gt; &lt;rect x="71" y="50" width="20" height="20" class="p1" id="p1_2_1" /&gt; &lt;rect x="92" y="50" width="20" height="20" class="p1" id="p1_3_1" /&gt; &lt;rect x="113" y="50" width="20" height="20" class="p1" id="p1_4_1" /&gt; &lt;rect x="134" y="50" width="20" height="20" class="p1" id="p1_5_1" /&gt; &lt;!-- etc etc, 200 rect in total--&gt; &lt;/svg&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload