D3.js selection.size() Function

The selection.size() function in D3.js is used to calculate and return the size of the selection. It counts the total element in the selection and returns its size.
Syntax:
selection.size();
Parameters: This function does not accept any parameters.
Return Value: This function returns a Numerical value.
Example 1: When selection is non-empty.
HTML
<!DOCTYPE html> <html lang="en"> Â Â <head> Â Â Â Â <meta charset="UTF-8"> Â Â Â Â <meta name="viewport" path1tent= Â Â Â Â Â Â Â Â "width=device-width,initial-scale=1.0"> Â Â Â Â <script src= Â Â Â Â </script> Â Â Â Â <script src= Â Â Â Â </script> </head> Â Â <body> Â Â Â Â <div>Geeks for Geeks </div> Â Â Â Â <div></div> Â Â Â Â <div></div> Â Â Â Â <div></div> Â Â Â Â <div></div> Â Â Â Â Â Â <script> Â Â Â Â Â Â Â Â let selection = d3.selectAll("div") Â Â Â Â Â Â Â Â let div = selection.size(); Â Â Â Â Â Â Â Â console.log(div) Â Â Â Â </script> </body> Â Â </html> |
Output:
5
Example 2: When selection is empty.
HTML
<!DOCTYPE html> <html lang="en"> Â Â <head> Â Â Â Â <meta charset="UTF-8"> Â Â Â Â <meta name="viewport" path1tent= Â Â Â Â Â Â Â Â "width=device-width,initial-scale=1.0"> Â Â Â Â <script src= Â Â Â Â </script> Â Â Â Â <script src= Â Â Â Â </script> </head> Â Â <body> Â Â Â Â <script> Â Â Â Â Â Â Â Â let selection=d3.selectAll("h2") Â Â Â Â Â Â Â Â let size=selection.size(); Â Â Â Â Â Â Â Â console.log(size) Â Â Â Â Â Â </script>Â </body> Â Â </html> |
Output:
0
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, zambiatek Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!



