Ashwin
Ashwin

Reputation: 12411

How to find first parent element in jquery

Conside below html -

<div class="container1">
   <div class="container2">
      <div class="container3">
         <div class="container4">
             <div class="element">
             ...
         </div>
      </div>
   </div>
</div>

if I want to get <div class="element"> element and I have reference to the container1. In jquery what I do is,

$(".container1").find(".element")

instead of -

$(".container1").children().children().children().find(".element")

This is process to find any child element when I have reference to any of the parent element. But instead when I have reference to a child element and want to get parent element then every time I have to go one level up -

$(".element").parent().parent().parent().parent()

and I can't do like this -

$(".element").findParent()

I have not come across any method like findParent() in jquery. Is there which I am not aware of? Or is it not there for some reason?

Upvotes: 13

Views: 44112

Answers (3)

Paul Basenko
Paul Basenko

Reputation: 1015

To get the first parent personally I use the following construction:

var count_parents = $(".element").parents().length;
$(".element").parents().eq(count_parents - 1);

Hope, it will be helpful for someone.

Upvotes: 1

thecodeparadox
thecodeparadox

Reputation: 87073

$(".element").parents();

will give all parents of .element(including html and body)

DEMO

To find any specific parent, suppose container1 then

$('.element').parents('.container1')

DEMO

jQuery .parents() generally find all parents, but if you passed a selector then it will search for that.

Upvotes: 29

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123387

just use

$(".element").closest('#container1');

if no ancestor with that id is found then

$(".element").closest('#container1').length will be 0

Upvotes: 14

Related Questions