Search parent elements in JQuery

Posted on 07-05-2013 09:07 by graham
To search through all parents elements of a given element in JQuery, use the parents function with some selector.

Search all parents


The code below searches for all parents of some item and adds a class parent-class to them:
$("#item-id").parents().addClass("parent-class");

Search parents with selector


We can do the same restricting the searched parents to those with class search-class:
$("#item-id").parents(".search-class").addClass("parent-class");
Comments

 

Add comment

Has this tutorial been helpful to you? Or do you see anything wrong? We appreciate your opinion!
Your comment:
Show formatting hints
HTML is disallowed, but in your text you can use the following markup
  • [code][/code] for a block of code
  • [tt][/tt] for inline code
  • [link]link href|link anchor[/link] for links
  • [b][/b] for bold text
Email:
+ Ask a question
If you have a technical question related to programming and computers, ask it here. Other users will help you solve it!
Unanswered questions
Share your knowledge by helping others solve their problems