Does querySelectorAll() accept ('div.element:first')
this type of argument? I need to convert below jQuery method in VanillaJS
jQUery :
$li = $(this)
$li.find('div.element:first')
Vanilla :
var li = event.target;
li.querySelectorAll('div.element:first');
But the Vanilla script is not working as same as jQuery. Someone please suggest any better solution
jQuery's :first
reduces the set of matched elements to the first in the set.
In other words, you get the first element matching div.element
.
To do the same in plain javascript, all you have to do is call querySelector
without the All
part
var first = li.querySelector('div.element');
As querySelector
will return the first element that matches the specified selector anyway
This of course only works if li
is a single element, querySelector
doesn't work on collections the way jQuery's find()
does.
If li
is not a single element, you have to iterate, but since you're only looking for the first element, you could just do
var first = li[0].querySelector('div.element');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With