JQuery and SVG - how to find the 'g' tag
Asked Answered
A

2

8

Imagine this:

<svg>
    <g id="node1" class="node"></g>
    <g id="node2" class="node"></g>
</svg>

How can I find the 'g' tag, I want that all tags could be clicked, and not just 'node1' or 'node2'. I've tried simular to this, but could not get it work.

$('g').click(function(){
    alert("Hellooooo");
});
Anciently answered 11/6, 2013 at 11:47 Comment(2)
Unable to replicate. $('g').click() works fine. jsfiddle.net/ZLnJwHiles
Hmm, that's strange. I've tried it again and it works for me to.Anciently
U
11

Use find() method for more info visit this

For eg $("body").find("p").css("background-color","#f00"); sets all body's <p> element background-color to red.

For your question try this:

$("svg").find("g").click(function(){

// your jquery code here

}
);
Uncharitable answered 11/6, 2013 at 11:49 Comment(7)
Thank you so much! Appreciate it.Anciently
This... is a silly answer. $('svg').find('g') is exactly the same as $('g') but with an extra unnecessary method call. Equally you can just use $('p').css({...});. No need for find() here at all.Hiles
@JamesDonnelly what happen if inside other tags is also "g" then he need to find within "svg" only.Uncharitable
@C-Link g is only a valid SVG tag. Unless developing a shadow DOM site (which is unlikely in its current state), g will always be the child of svg.Hiles
Oh! I don't know svg so I'd provided that answer. Anyway thanx.Uncharitable
@JamesDonnelly also in his question he tried but not worked saying, why? I think here is find() method is right to choose.Uncharitable
For flat <svg> docs, use $('g'), but when dealing with nested <svg> inside <svg>, I'd use $('svg')[0].find('g') to navigate the DOM tree.Calgary
A
2

Thanks to C-Link I've solved this.

To be sure only the nodes are clickable I've wroted:

$("svg").find("g.node").click(function(){
    alert("Lolol");
});

And it works fine.

Anciently answered 11/6, 2013 at 12:30 Comment(1)
+1. Don't deserve a downvote as it is good to know the long way and short way. As explained above, in some cases, you'd need the long method.Calgary

© 2022 - 2024 — McMap. All rights reserved.