Dave Mak
Dave Mak

Reputation: 103

d3.js selectAll method does not select all elements?

I'm new to d3.js. I am told by the documentation that .selectAll "Selects all elements that match the specified selector string". But when I try to used3.selectAll("p").selectAll("b")to get all belements in below html code, the last b element is not selected :

<p>
    <b>selected</b>
    <b>selected</b>
    <h4>some word</h4>
    <b>not selected</b>
</p>

enter image description here

can someone walk me through on this? Thanks!

var selection = d3.selectAll("p").selectAll("b");

console.log("b elements selected: ", selection.size());
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<p>
        <b>selected</b>
        <b>selected</b>
        <h4>some word</h4>
        <b>not selected</b>
    </p>

Upvotes: 3

Views: 227

Answers (1)

Andrew Reid
Andrew Reid

Reputation: 38151

A p element cannot contain a h4 element. A p can only contain phrasing content, such as a b element. In your case the h4 tag closes the p:

The end tag may be omitted if the <p> element is immediately followed by an ... <h4>, ... (source)

So your third b isn't inside a p at all. Which is why you can't select it as a child of the p. You could try two p elements, with the h4 between, or you could use a span with the appropriate styles:

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

<p>
    <b>selected</b>
    <b>selected</b>
</p>
    <h4>some word</h4>
<p>
    <b>not selected</b>
</p>

<script>
var selection = d3.selectAll("p").selectAll("b");

console.log(selection.size());


</script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

<p>
    <b>selected</b>
    <b>selected</b>
    <span>some word</span>
    <b>not selected</b>
</p>

<script>
var selection = d3.selectAll("p").selectAll("b");

// for demonstration as all `b` elements are in the first `p` element.
var selection2 = d3.select("p").selectAll("b");


console.log(selection.size());
console.log(selection2.size());


</script>

Upvotes: 5

Related Questions