I need to check if a <ul>
exists inside an <li>
that has the class .sub-menu
and if it does, add a class to the anchor tag inside the <a>
tag above the .sub-menu
Using jQuery to see if a div has a child with a certain class
How to detect if any child elements within a parent element has a certain class?
Above are my reference answers.
I'm trying to loop through each list and check with .find()
I don't understand how to use .find()
in a loop or each()
function and how to tie it to the this
keyword.
I also tried .children()
but it throws that children() is not a function
See the first example below.
$(function(e) {
var getMenuItems = $(".item");
for (var i = 0; i < getMenuItems.length; i++) {
if (this.find("ul.sub-menu") !== 0) {
console.log("sub-menu found")
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li class="item">
<a href="#"></a>
<ul class="sub-menu">
<li></li>
</ul>
</li>
<li class="item">
<a href="#"></a>
</li>
<li class="item">
<a href="#"></a>
<ul class="sub-menu">
<li></li>
</ul>
</li>
<li class="item">
<a href="#"></a>
</li>
</ul>
it throws this.find is not a function
- why? Can you not use this
in .find()
? Is this
not referring to what I think it is?
I don't understand.
I tried this too:
$(function(e) {
var getMenuItems = $(".item");
for (var i = 0; i < getMenuItems.length; i++) {
if (getMenuItems.find("ul.sub-menu") !== 0) {
console.log("sub-menu found")
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li class="item">
<a href="#"></a>
<ul class="sub-menu">
<li></li>
</ul>
</li>
<li class="item">
<a href="#"></a>
</li>
<li class="item">
<a href="#"></a>
<ul class="sub-menu">
<li></li>
</ul>
</li>
<li class="item">
<a href="#"></a>
</li>
</ul>
The error goes away, but it logs 4 times when I expect it to be 2. This is because it's just looping 4 times I think? Howcome .find()
doesn't work in this example? What is this
exactly referring to in these examples? My understanding was that if you use this
in a loop it's referring to each element it's looping through. But I guess that's not the case.
What needs to change with this code snippet so that I can hit the 2 sections with .sub-menu
and modify the DOM accordingly?