Adding FontAwesome icons to a D3 graph

You need to use the proper Unicode inside a normal text element, and then set the font-family to "FontAwesome" like this:

 node.append('text')
    .attr('font-family', 'FontAwesome')
    .attr('font-size', function(d) { return d.size+'em'} )
    .text(function(d) { return '\uf118' }); 

This exact code will render an "icon-smile" icon. The unicodes for all FontAwesome icons can be found here:

http://fortawesome.github.io/Font-Awesome/cheatsheet/

Be aware that you need to adapt the codes in the cheatsheet from HTML/CSS unicode format to Javascript unicode format so that  must be written \uf118 in your javascript.


Thanks to all that replied. My final solution is based on the answer by CarlesAndres:

g.append('text')
    .attr('text-anchor', 'middle')
    .attr('dominant-baseline', 'central')
    .attr('font-family', 'FontAwesome')
    .attr('font-size', '20px')
    .text(function(d) { return ICON_UNICODE[d.nodeType]; });

Be careful with your CSS: it takes precedence over the SVG attributes.

And this is the way it looks:

Node Graph

The good thing about this, compared to the foreignObject solution, is that events are properly handled by D3.