Here is an example of some HTML code:
<ul id="myList">
<li>
<a class="myListItem li-selected">One</a>
</li>
<li>
<a class="myListItem">Two</a>
</li>
<li>
<a class="myListItem li-selected">Three</a>
</li>
<li>
<a class="myListItem">Four</a>
</li>
<li>
<a class="myListItem">Five</a>
</li>
</ul>
The li-selected class is applied when the corresponding <li> tag is selected. I want to use jQuery's $(document).ready() function to check if any <li> elements have the li-selected class. This will result in a boolean value that can be passed as a parameter to another function.
I tried the following, but it does not return true as expected:
$(document).ready(function() {
.
.
.
var hasSelectedItems = $("#myList li").find("a").hasClass("li-selected");
console.log(hasSelectedItems);
.
.
.
});
Expected output:
- If hasSelectedItems === true, then at least one <li> is selected.
- If hasSelectedItems === false, then no <li> is selected.
SOLVED
It turns out there was nothing wrong with the way I checked for the existence of the li-selected class, but rather with when I was checking it. I mistakenly placed the
var hasSelectedItems = $("#myList li").find("a").hasClass("li-selected");
part of the code before the class had been added. I rearranged the code to run after the elements were re-rendered with the li-selected class, and now it works correctly.