Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do we convert jQueryn $li.find('div.element:first') in VanillaJS

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

like image 426
supun94 Avatar asked Dec 19 '22 04:12

supun94


1 Answers

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');
like image 161
adeneo Avatar answered Dec 24 '22 01:12

adeneo