简体   繁体   中英

Can selectAll() in d3 js take css style also as parameter?

I am new to javascript and d3. While working on few examples I came across some lines like this : var legend = svg.selectAll(".legend")

I saw this while creating a legend for my scatterplot. This was part of the accepted solution in this link

  1. Why are we giving .legend as a parameter?
  2. Is .legend a CSS style?
  3. In general what all can we pass as argument to selectAll()?

I have worked out these set of examples ( Scott Murray's tutorial ) but I am still confused on how selectAll works. Any guidance/explanation/links to read is really appreciated.

d3.selectAll(selector)

Selects all elements that match the specified selector string. The elements will be selected in document order (top-to-bottom). If no elements in the document match the selector, or if the selector is null or undefined, returns an empty selection. For example, to select all paragraphs:

var paragraph = d3.selectAll("p");

1) In your example, .legend is a class selector . It is being passed as an argument to selectAll to match all DOM elements that have a class of legend .

2) .legend is not a CSS style itself. But it can be used in CSS as a selector to apply some style properties to the elements that match said selector.

3) selectAll accepts only one argument: a selector string. That could simply be "p" or it could be ".content .items > li" .


Have a look below how we can use both CSS & D3 to apply different styles.

 d3.selectAll(".highlight") .style({ "color": "green" }) 
 nav a { color: red } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> <nav> <ul> <li><a href="#nowhere" title="Lorum ipsum dolor sit amet">Lorem</a></li> <li><a href="#nowhere" title="Aliquam tincidunt mauris eu risus">Aliquam</a></li> <li><a href="#nowhere" title="Morbi in sem quis dui placerat ornare" class="highlight">Morbi</a></li> <li><a href="#nowhere" title="Praesent dapibus, neque id cursus faucibus">Praesent</a></li> <li><a href="#nowhere" title="Pellentesque fermentum dolor" class="highlight">Pellentesque</a></li> </ul> </nav> 

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