admin管理员组

文章数量:1401384

I use this jQuery plugin to load SVG image into a div. I'd like to get all the element IDs from the SVG XML data which contain an ID attribute. For example, in my SVG image I have circle and polygon elements with ID attributes, but a rect element without ID attribute. I want to get these two with IDs from the XML.

How do I do this?

I have tried this in the onLoad method of svg function.

$("#image svg").each(function() {
    $("#list").append("<option>" + this.id + "</option>");
});

#image is the container for the svg element and #list is the select tag.

I use this jQuery plugin to load SVG image into a div. I'd like to get all the element IDs from the SVG XML data which contain an ID attribute. For example, in my SVG image I have circle and polygon elements with ID attributes, but a rect element without ID attribute. I want to get these two with IDs from the XML.

How do I do this?

I have tried this in the onLoad method of svg function.

$("#image svg").each(function() {
    $("#list").append("<option>" + this.id + "</option>");
});

#image is the container for the svg element and #list is the select tag.

Share Improve this question edited Nov 19, 2013 at 17:24 MikkoP asked Nov 19, 2013 at 17:09 MikkoPMikkoP 5,09217 gold badges61 silver badges108 bronze badges 2
  • 1 Please post what you have tried so far. We are happy to help you with the code you have. – Felix Kling Commented Nov 19, 2013 at 17:18
  • @FelixKling I added the code I've tried. – MikkoP Commented Nov 19, 2013 at 17:24
Add a ment  | 

2 Answers 2

Reset to default 3

Assuming the SVG is added to the page properly, you can use the "has attribute selector" to select all elements with an ID:

$("#imag > svg [id]").each(function() {
    $("#list").append("<option>" + this.id + "</option>");
});

Are you sure it's not working?

I've created a fiddle with your code

$("#image svg").each(function() {
    $("#list").append("<option>" + this.id + "</option>");
});    

and it looks fine to me.

Edit: Replace the second line with this:

$("#list").append("<option style='display:" + ((this.id.length>0)?'inline':'none') + ";'>" + this.id + "</option>");

to show only the ones with the ID. Or just put a check(length>0, or something) before appending the option tag(which would probably be easier to understand/modify later on, I just like to use ternary operators :p )

本文标签: javascriptjQuery get all elements inside SVG with ID specifiedStack Overflow