0
console.log($('svg.datamap').html())

I am trying to select a SVG element with class attribute as "datamap". It doesn't work because I am creating the svg element dynamically. How do I solve this? Or is there a way to select dynamically created elements in javascript?

Rakesh Adhikesavan
  • 8,945
  • 14
  • 44
  • 67
  • when you create the element dynamically you could add the class to it then with `$.addClass()`or give the element an id with `$.attr()` and use that later – source.rar Jun 08 '14 at 21:31
  • That doesn't make sense. You can't select elements that don't exist yet, and you can't get the *content* of elements that don't exist. I mean seriously, how do you expect this to work? Since you accept the answer that suggested to use event delegation, even though you didn't mention events at all, I assume that's your original problem and in that case it's a duplicate. – Felix Kling Jun 08 '14 at 23:10
  • 1
    If this is for the d3.js library DataMaps, you should put this logic inside the `done` handler DataMaps provides. – markmarkoh Jun 17 '14 at 19:39

1 Answers1

2

You need to bind to something that exists at page load and then delegate off of that. A basic example might be:

$('body').on('click','svg.datamap',function() {
    //do something with svg.datamap
});
Stevangelista
  • 1,749
  • 1
  • 9
  • 15