Arihant
Arihant

Reputation: 4047

Get element click on inside an SVG Element

I have two nested <svg> elements as follows:

<svg id="main_svg">
    <svg data="business" id="something">
        <rect>
            // Code for rectangle
        </rect>
    </svg>
</svg>

How can I get the id of the <svg> tag inside main_svg?

I tried the contextmenu event handler with this.id but it always returns main_svg:

$("svg").contextmenu(function(e) {
    e.preventDefault();
    console.log(this.id);
});

How can this be done? Are there any better approaches? I am happy with either events: onclick or contextmenu.

Upvotes: 0

Views: 895

Answers (1)

ssc-hrep3
ssc-hrep3

Reputation: 16089

You can use the jQuery function $('svg').find("> svg") to find every direct child-<svg>-element of an <svg> element.

$('svg').find("> svg").each(function() {
    var id = $(this).attr("id");
    console.log(id);
});

See the jsFiddle: https://jsfiddle.net/kyjn6z87/

Upvotes: 2

Related Questions