Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select an element which parent is not specified class?

I want to hide an element if its parent does not have a certain class:

HTML

<li class="current_page_parent">     <a href="parent.html">Parent</a>     <ul class="children">         <li>foo</li>         <li>bar</li>     </ul> </li> 

jQuery

jQuery("ul.children").hide(); 

Currently always hides <ul class="children"> regardless of class. I would like to close it only if parent is :not an <li class="current_page_parent">.

I've tried:

jQuery("ul.children:not(:parent.current_page_ancestor)").hide(); 

with no luck.

like image 976
Naoise Golden Avatar asked Jul 22 '11 01:07

Naoise Golden


People also ask

How do you select an element that does not have a specific class?

To select element that does not have specific class with JavaScript, we can use the document. querySelector method with the :not pseudoclass. const li = document. querySelector("li:not(.

How do you know if an element has a parent with a class?

Use the parentElement property to select the parent of the element. Use the classList. contains() method to check if the parent contains the class. The method returns true if the element's class list contains the class and false otherwise.


2 Answers

The best way I think:

$(".children").not(".current_page_parent .children").hide(); 

JSFiddle

like image 128
Artem P Avatar answered Sep 20 '22 13:09

Artem P


Try this:

jQuery("li:not(.current_page_parent) ul.children").hide(); 
like image 34
Chandu Avatar answered Sep 21 '22 13:09

Chandu