Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if parent element contains certain child element using jQuery

Tags:

html

jquery

<div id="example">   <div id="test"></div> </div>  <div id="another">Blah</div> 

I want to set $('#another').hide() but only if #example contains a child element called#test, is this possible? It seems like it would be.

like image 800
UserIsCorrupt Avatar asked Mar 23 '12 03:03

UserIsCorrupt


People also ask

Can we get the children element from the parent element using jQuery?

jQuery children() method is used to get the direct children of the selected HTML element. You can use children() method to traverse through the child elements of the selected parent element.

What is the use of parent () and child () method in jQuery?

It is a jQuery Selector used to select all elements that are the direct child of its parent element. Parameter Values: parent: Using this, the parent element will be selected. child: Using this, the direct child element of the specified parent element will be selected.


2 Answers

Use length

if ($('#example').find('#test').length) {     // found! } 
like image 62
elclanrs Avatar answered Sep 24 '22 16:09

elclanrs


I think what you are looking for is the following

if (jQuery.contains($('#example'), $('#test')) {     $('#another').hide(); } 

This might work as well, not sure off the top of my head.

if ($('#test', $('#example')).size() > 0) {     $('#another').hide(); } 
like image 30
Mike Geise Avatar answered Sep 25 '22 16:09

Mike Geise