querySelector search immediate children

Viewed 80669

I have some jquery-like function:

function(elem) {
    return $('> someselector', elem);
};

The question is how can i do the same with querySelector()?

The problem is > selector in querySelector() requires parent to be explicitly specified. Is there any workaround?

10 Answers

If you want to eventually find direct children (and not e.g. > div > span), you can try Element.matches():

const elem = document.body
const elems = [...elem.children].filter(e => e.matches('b'))

console.log(elems)
<a>1</a>
<b>2</b>
<b>3</b>
<b>4</b>
<s>5</s>

Related