Filth
Filth

Reputation: 3228

How to get parent using $(this)

I'm trying to further my understanding of traversing and correctly using $(this).

I understand $(this) is used in reference to the context. However, say I have three items that are identical to each other (HTML-wise) and if a user clicks on an input, I want the events to not only happen for the item the user selected, but be able to access the parent element ".item" as well. This way, I can hide other elements within ".item" because, again, the context would be the "input" that the user clicked.

This is where I am confused. When a user clicks on the input ($('input').on('click', doSomething);), I am limited to the context of the input - nothing is inside the input, so I want to access other elements that are out of the input context.

I then try and use $(this) to say I only want THIS event to happen for THIS item only, not affecting ALL items.

Here is a code example: JSFIDDLE

I've tried researching this and I can't find much information on an instance like this so hopefully this could benefit others too. Feel free to make edits to the content / heading as I've tried to be as specific as possible.

Upvotes: 0

Views: 125

Answers (2)

Philipp Munin
Philipp Munin

Reputation: 5903

This should be your click-handler code :

function doSomething(event) {
    $(event.target).parent().find('ul').hide();
}

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074138

To get the immediate parent(s) of the element(s) in a jQuery set: parent. (If your set has only one element, as $(this) will, that will give you that element's immediate parent.)

To find the closest element(s) to the elements(s) in a jQuery set matching a given selector, starting with the current element(s): closest. (If your set has only one element, as $(this) will, that will give you the first element matching a selector starting with that one element, then looking at its parent, then its parent, etc.)

Upvotes: 8

Related Questions