Posted in jquery
4
4:22 am, June 15, 2021

jquery check if a sub element exists

this can be done with .length

HTML

<div class="menu">
<ul>
<li><a href="#!">menu</a>
<ul>
<li><a href="#!">sub1</a>
<ul>
<li><a href="#!">sub2</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>

Javascript

$(document).ready(function(){
	$('.menu > ul > li > a').click(function(e) {
		if($(this).closest('li').find('ul').length) {
    	  var message = "the 1st ul li a also contains a ul";	
          console.log(message);
          alert(message);
		}
	});
});

View Statistics
This Week
33
This Month
130
This Year
0

No Items Found.

Add Comment
Type in a Nick Name here
 
Search Code
Search Code by entering your search text above.
Welcome

This is my test area for webdev. I keep a collection of code snippits here, mostly for my reference. Also if i find a good site, i usually add it here.

Join me on Substack if you want me to send you a collection of the things i have done or found or read for the week. Or follow me on twitter if you prefer, i dont post much but i probably should!

❤👩‍💻🕹

Random Quote
"Let us prepare our minds as if we'd come to the very end of life. Let us postpone nothing. Let us balance life's books each day ... The one who puts the finishing touches on their life each day is never short of time."
Seneca