Reputation: 830
Here is my code snippet:
I was trying to understand how you can get at the properties of a DOM object using d3. In this case after the object has returned an event. So for example how would I access the 'x1' attribute.
var svg = d3.select('svg')
.append('polyline')
.attr('x1', 20)
.attr('y1', 100)
.attr('x2', 100)
.attr('y2', 100)
.attr('points', "20,100 100,100 100,100 180,100")
.attr('fill', 'none')
.attr('stroke', palette.gray)
.attr('marker-start', "url(#triangle)")
.attr('marker-mid', "url(#triangle)")
.attr('marker-end', "url(#triangle)")
.on('click', function(){
console.log('polyline click');
console.log(this);
});
I used
I finally found the solution was to use: d3.select(this).attr("cx")
What is 'this'? If I print 'this' to the console I seem to get the DOM object back as
<polyline x1="20" y1="100" x2="100" y2="100" points="20,100 100,100 100,100 180,100" fill="none" stroke="#708284" marker-start="url(#triangle)" marker-mid="url(#triangle)" marker-end="url(#triangle)">
It seems a bit 'hacky' to have to select the element again. Have I missed a trick here?
Upvotes: 2
Views: 3119
Reputation: 34489
Nope you've not missed anything.
this
is indeed the DOM element as you logged, the problem is that attr()
is a D3 function, specifically on a d3.selection.
What you need to do is convert the DOM element to a selection so you can take advantage of the d3 helper functions. The way to do that is just as you had
d3.select(this)
Upvotes: 5