1

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"))?

1 Answer 1

2

.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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.