user2717621
user2717621

Reputation: 125

how to get svg element type

i have a question, how can i get the type of svg element, btw i use d3.js

i have sth like this

var selectedElement = svg.select("." + STYLE.selected);

         if (selectedElement instanceof SVGCircleElement){
            alert("here circle");
            selectedElement.style("fill", function(){return d3.rgb(d3.select(this).attr("fill"));});
         }
           if (selectedElement instanceof SVGPathElement){
             alert("here path");
                appendMarkerm(selectedElement,false);

         }

but it seems didnt work , can someone help out here ,thanks !!


***finally, i made it work like this*** 

var selectedElement = svg.select("." + STYLE.selected);
           if (selectedElement.node() instanceof SVGCircleElement){
            selectedElement.style("fill", function(){return d3.rgb(d3.select(this).attr("fill"));});
         }
           if (selectedElement.node() instanceof SVGPathElement){
            changeMarkerStyle(selectedElement,false); 
         }

cauz selection.node() will return the first element of the selection

Upvotes: 6

Views: 9262

Answers (1)

Sirko
Sirko

Reputation: 74046

Just use the tagName property:

svg.select("." + STYLE.selected)
   .call( function(){

      switch( selectedElement.tagName.toLowerCase() ) {
        case 'circle': 
          alert("here circle");
          this.style("fill", function(){return d3.rgb(d3.select(this).attr("fill"));});
          break;

        case 'path':
          alert("here path");
          appendMarkerm( this, false );
          break;
      }

    });

EDIT

d3js' select() does not return the element itself, but a d3js wrapper for it (very much like in jQuery, e.g.). So the easiest way, would be to use the call() method to apply a function to all matches (in the case of just select() this is just one).

Upvotes: 5

Related Questions