N8Core
N8Core

Reputation: 25

Find 3rd Parent div up for each div with class, then add css to it

SO for each div with ".protected_wrap" class I am needed to go up 3 levels, then add a class or css to that div.

my code

$( "div.protected_wrap" ).parents().eq(2).className( "hidephotos" )

$( "div.protected_wrap" ).parents().eq(2).css( "display", "none" );

the 3rd div up is ".photo_item_wrap" but nothing is being done as far as adding css or a class.

seems nothing is happening though

Upvotes: 0

Views: 158

Answers (1)

VVV
VVV

Reputation: 7593

You should look into .closest()

It gets the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

This should do the trick:

$( "div.protected_wrap" ).closest('.photo_item_wrap').css( "display", "none" );

You could also use .parents() like you're doing but you need to specify the selector like this

$( "div.protected_wrap" ).parents('.photo_item_wrap').css( "display", "none" );

The thing is with .parents(); it will find all the ancestors with the specified selector. So if you have multiple parent elements with that selector, I suggest you use .closest()

Side notes

  1. You can use .hide() instead of .css("display", "none")
  2. To add a class to an element, use .addClass()

Upvotes: 2

Related Questions