user4602228
user4602228

Reputation:

How to use querySelector to look up only direct children, without further descendants?

How can I select a first child of type X which is a direct descendant of the element using the elements querySelector

For example :

<div id="target">
   <span>1</span>
   <span>2</span>
   <span>3</span>
   <div>
      <span>4</span>
   </div>
</div>

I would like to select only first child SPANs of the target div using querySelector.

target.querySelector('span'); // This would return all spans in target

The other alternatives I know and wouldn't like to use :

Using CSS :

#target > span

Using JS :

[].filter.call(target.children, f=>{ return f.tagName == 'SPAN' })

I would like to use querySelector anyway...

is there a way to call querySelectorAll on a given element, to select only first child elements?

Upvotes: 14

Views: 52634

Answers (6)

pomber
pomber

Reputation: 23980

If you don't want to depend on the #target selector, you can use the :scope pseudo-class:

const target = document.querySelector("#target");
const child = target.querySelector(":scope > span");

Upvotes: 22

user8108377
user8108377

Reputation:

in this solution i assume you know how many item

you have to select

var x = document.querySelectorAll("span");
 x[0].style.backgroundColor = "red";
 x[1].style.backgroundColor = "red";
 x[2].style.backgroundColor = "red";

the result will be the same as

#target > span {
  background-color:red;
}

Upvotes: 1

Dhruvil21_04
Dhruvil21_04

Reputation: 2189

Why not use this if you want to use querySelector anyway:

target.querySelector('#target span').first();

OR

target.querySelector('#target span:first-child');

Upvotes: -1

Will Reese
Will Reese

Reputation: 2841

querySelector gets the first element that matches the selector. Just use the direct descendant selector with it. You don't need any other pseudo selectors.

var target = document.querySelector("#target");
var child = target.querySelector("#target > span");

Upvotes: 17

Usman Mughal
Usman Mughal

Reputation: 93

var target = document.querySelector('#target > :first-of-type');
target.style.color = 'red';
<div id="target">
   <i>1</i>
   <span>2</span>
   <b>3</b>
   <div>
      <span>4</span>
   </div>
</div>

Upvotes: 0

Chiller
Chiller

Reputation: 9738

You can use :first-child if you want to get the first child of its parent

target.querySelector('span:first-child');

Or you can use :first-of-type if you want to specify the type like in your case is a span

target.querySelector('span:first-of-type');

See example:

var target = document.querySelector('span:first-of-type');
target.style.color = 'red';
<div id="target">
   <span>1</span>
   <span>2</span>
   <span>3</span>
   <div>
      <span>4</span>
   </div>
</div>

Upvotes: 12

Related Questions