DEV Community

Chittoji Murali Sree Krishna
Chittoji Murali Sree Krishna

Posted on

how to Change jquery to Vanilla javascript

$(this).parent().parent().find(".imgHide").toggleClass("imgShow"); 
Enter fullscreen mode Exit fullscreen mode

to javaScript
for parent() we can use parentElement
for toggleClass() we can use .classList.toggle("class")
but for .find() i am not able to get any alternative in vanilla js.

Top comments (8)

Collapse
 
jorik profile image
Jorik

A somewhat related element method is closest. This will help you find a parent, or the node itself, that matches the selector. This helps to make your code stronger against changes in your DOM structure (the .parent().parent() chain)

developer.mozilla.org/en-US/docs/W...

Collapse
 
cmuralisree profile image
Chittoji Murali Sree Krishna

i tried the closest method but it didnt worked

Collapse
 
peerreynders profile image
peerreynders • Edited

It wouldn't as looks in the opposite direction to jQuery's find() or the Web API's querySelector[All]() - which starts at the Element and then looks at the descendent elements (away from the document root).

The Web API's closest() is complementary as it starts at the Element and then looks at the ancestor elements (towards the document root). See also jQuery's .closest().

That being said querySelector() has been around longer than Element.closest().

Thread Thread
 
cmuralisree profile image
Chittoji Murali Sree Krishna

okay now i understand, really thanks for the entire details, really appericiate your help

Collapse
 
Collapse
 
cmuralisree profile image
Chittoji Murali Sree Krishna

thanks for the info peerreynders

Collapse
 
martini profile image
Martin

Googling "jquery .find vanilla js" gave the following result: stackoverflow.com/a/53824604

Maybe check it out and see if that works for you.

Collapse
 
cmuralisree profile image
Chittoji Murali Sree Krishna

thanks for info Martini