Just a learner
Just a learner

Reputation: 28652

How use JavaScript to query on selector result properly?

I have the following piece of HTML.

<div id="outer"><b class="dest">something</b>
    <div id="test"><b class="dest">unwanted stuff</b></div>
</div>

Let's say I already have a reference to the outer element with document.querySelector("#outer"). How can I query all b elements with the dest class and are the first child of its parent? I tried document.querySelector("#outer").querySelector("b.dest") and document.querySelector("#outer").querySelector("b.dest:first-child") but only the first b element has returned. How can I get both b elements (through the result of document.querySelector("#outer"))?

Upvotes: 1

Views: 557

Answers (1)

itsisaac19
itsisaac19

Reputation: 549

.querySelector only selects one element max.

.querySelectorAll Returns an array-like node list.

You want:

var bElements = document.getElementById("outer").querySelectorAll('b.dest:first-child');

This will return an array of all elements that:

  • Have a parent with an id of outer
  • have the class dest
  • are the first-child of their parent

Then you can access each element just like an array, ex.

bElements[0]

DEMO:

var bElements = document.getElementById("outer").querySelectorAll('b.dest:first-child');

console.log(bElements)
<div id="outer"><b class="dest">something</b>
    <div id="test"><b class="dest">unwanted stuff</b></div>
</div>

Upvotes: 2

Related Questions