pwerth
pwerth

Reputation: 210

Select divs by ID prefix in d3

I have a bunch of divs with the following ids:

<div id = "abox"></div>

<div id = "bbox"></div>

<div id = "cbox"></div>

I would like to select all of these divs using d3, something like

d3.selectAll("# *box) where * indicates any string. Is this possible?

Upvotes: 1

Views: 2979

Answers (3)

mdml
mdml

Reputation: 22882

You can add a class to each of those <div>s, and then select them using a class selector. (Note that elements can have multiple classes, just separate them with a space.) Here's an example:

HTML

<div id="abox" class="class1 class2 star-box">...</div>
<div id="bbox" class="class1 class3 star-box">...</div>
<div id="cbox" class="class2 class4 star-box">...</div>

Javascript

var divs = d3.selectAll(".star-box")

Upvotes: 3

ckersch
ckersch

Reputation: 7687

You can select all divs and then use the filter method on the collection to do this.

d3.selectAll('div').filter(function(){
  return d3.select(this).attr('id').substr('box') !== -1;
});

Upvotes: 3

rkgibson2
rkgibson2

Reputation: 169

You could try [id*="box"], if d3 uses all the jQuery selectors.

Upvotes: 1

Related Questions