Issue
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?
Solution
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");
Answered By - Will Reese
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.