简体   繁体   中英

How to select all elements that have (any) class

I am using D3 selectAll to perform a transformation. I have around 260 paths but only 80 of them have a class.

How should I select all the paths that have class?

You don't need D3 to check if an element has a class, but here is a D3-based answer. When using a D3 getter...

selection.attr("class")

... it will return null for elements without a class.

Therefore, all you need is checking the getter.

For instance, suppose you have this SVG with 5 paths, 3 of them having a class:

<svg>
  <path></path>
  <path class="foo"></path>
  <path class="bar"></path>
  <path class="baz"></path>
  <path></path>
</svg>

By using a getter inside a filter we can get only the elements with a class, even if the classes are different:

 const pathsWithClass = d3.selectAll("path") .filter(function() { return d3.select(this).attr("class") }); console.log("Elements with class: " + pathsWithClass.size())
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script> <svg> <path></path> <path class="foo"></path> <path class="bar"></path> <path class="baz"></path> <path></path> </svg>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM