D3 6 + FontAwesome 5

https://stackoverflow.com/questions/18416749/adding-fontawesome-icons-to-a-d3-graph

by diafour

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.2.0/d3.min.js"></script>
<!--
data-auto-replace-svg="nest" is not necessary for this example, but it can be useful for styling (e.g. bootstrap) and for event handling (e.g. jquery).
See: https://fontawesome.com/how-to-use/on-the-web/using-with/jquery 
-->
<script src="https://use.fontawesome.com/releases/v5.15.0/js/all.js" data-auto-replace-svg="nest" data-auto-></script>


<div id="html-btn">
<i class="fas fa-check-square"></i>&nbsp;icon in html code (click to toggle)
</div>

JavaScript

document.addEventListener('DOMContentLoaded', function () {
  var svg = d3.select("body")
    .append("svg")

  var btnGroup = svg.append("g")

  // FontAwesome 5 svg icon.
  btnGroup.append("g")
    .attr("width", 16) // These attributes are copied 
    .attr("height", 16) // by fontawesome onto new svg element.
    .attr("class", "fas fa-check-square");

  // A label for icon.
  btnGroup.append("text")
    .attr("x", 20)
    .attr("y", 13)
    .text("text with icon in SVG (click to toggle)");

  // Icon toggle function.
  const iconToggleFn = function() {
    var el = d3.select(this).select("svg[data-fa-i2svg]");
    el.classed("fa-check-square", !el.classed("fa-check-square"));
    el.classed("fa-square", !el.classed("fa-square"));
  };
  // jQuery version
  //const iconToggleFn = function() {
  //  $(this).find('svg[data-fa-i2svg]')
  //         .toggleClass('fa-check-square')
  //         .toggleClass('fa-square');
  //};

  // Use toggle function for SVG element and for HTML element.
  btnGroup.on("click", iconToggleFn);

  d3.select("#html-btn").on("click", iconToggleFn);
 
});