D3 js knows if svg form has class

I want to have a toggle button in svg form and scale it when the button is clicked, and then zoom in when I click it again, firstly, I added a class collapselike this. I want to delete a class if it has a classcollapse

g.append("circle")
    .classed("collapse", true)
    .attr("cx", 0)
    .attr("cy", 0)
    .attr("r", radius * 0.4 - 10)
    .attr("fill", color(radius * 0.4 - 10))
    .on("click", (d) ->
      if(hasClass("collapse")) # HOW DO I DO THIS
    )
+4
source share
4 answers

Musical_ut solution is correct, but it is supported only by the latest browsers (for example, Safari 6.0.5 will not work earlier, but - the release of June 5, 2013 )

, SVG DOM HTML DOM. classList.contains . (. jsfiddle SVG HTML)

[ ] , . (jsfiddle)

g.append("circle")
    .classed("collapse", true)
    .attr("cx", 50)
    .attr("cy", 50)
    .attr("r", radius * 0.4 - 10)
    .attr("fill", 'black')
    .on('click', function(d){
        this.setAttribute('class', '');
        // or if your element has other classnames as well
        // scan the class names, remove the "collapse" from it and push the new string into class.
        //if(this.className.baseVal.indexOf('collapse')>=0){ … }
    }
   );
+5

DOM API:

g.append("circle")
    .classed("collapse", true)
    .attr("cx", 0)
    .attr("cy", 0)
    .attr("r", radius * 0.4 - 10)
    .attr("fill", color(radius * 0.4 - 10))
    .on("click", (d) ->
      if(this.classList.contains("collapse")) {
        // ...
        // this.classList.remove('collapse')
      } else {
        // ...
        // this.classList.add('collapse')
      }
    )    

jQuery:

g.append("circle")
    .classed("collapse", true)
    .attr("cx", 0)
    .attr("cy", 0)
    .attr("r", radius * 0.4 - 10)
    .attr("fill", color(radius * 0.4 - 10))
    .on("click", (d) ->
      if($(this).hasClass("collapse")) {
        // ...
      }
    )

this DOM. , , D3-isque -. collapsed data, node, , class DOM.

+5

CoffeeScript, JavaScript. , d3.js:

.on "click", ->
  d3.select(this).classed("collapse", false) unless d3.select(this).select(".collapse").empty()
+1

, :

enter code hereg.append("circle")
.classed("collapse", true)
.attr("cx", 0)
.attr("cy", 0)
.attr("r", radius * 0.4 - 10)
.attr("fill", color(radius * 0.4 - 10))
.on("click", (d)) {

  var this_ = d3.select(this);

    if(this_.select(".collapse").attr("visibility") == "visible") {

      this_.select(".collapse").attr("visibility", "hidden");

    } else {

      this_.select(".collapse").attr("visibility", "visible");

    }

});
+1

All Articles