Reputation: 12913
After selecting an element by ID I find the ID to be undefined.
To illustrate this I put together this example (fiddle link)
Set up elements:
<pre id='output'></pre>
<input id='my-checkbox' type='checkbox'>
The d3 script:
d3.select('#my-checkbox')
.call(function(){
document.getElementById('output').outerHTML = this.id;
})
.on('click', function(){
document.getElementById('output').outerHTML = this.id;
});
This fills the pre element with "undefined" which persists even when clicking the box. On the other hand the script below works as I would expect:
d3.select('#my-checkbox')
.on('click', function(){
document.getElementById('output').outerHTML = this.id;
});
What is going on here? How can I access the element's ID within d3's call
function?
Upvotes: 0
Views: 841
Reputation: 1983
From the d3 documentation
Like function.call, invokes each registered callback for the specified type, passing the callback the specified arguments, with that as the this context. See dispatch.apply for more information.
The function you are looking for is each
.each(function(){
document.getElementById('output').outerHTML = this.id;
})
Upvotes: 1
Reputation: 610
You will get the element object as the first argument:
d3.select('#my-checkbox').call(function(s){
document.getElementById('output').outerHTML = s.attr('id');
});
Upvotes: 1