Is there a way to determine if an <a> element contains a certain class while it is contained within an <li> element?

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.

Answer №1

Here is a useful jQuery snippet to locate the a element within your code:

$(document).ready(function() {
    var linkCount = $("#myList li a.li-selected").length;
    if(linkCount > 0)
    {
     //Your logic goes here
    }
    else
    {
     //Do something different if there are no links
    }
});

Answer №2

To determine the size of anchor elements with a selected list class, you can use:

var selectedListItems = $("#myList li a.selected").length > 0 ;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Checking for null properties in Typescript objectsorHow to verify if a

What is a simple way to determine if the properties of an object in TypeScript are nullable? For example export default interface UserDto{ ID?:int; USER_NAME?:string; FIRST_NAME?:string; LAST_NAME?:string; USER_ROLE?: ...

Adding square elements to mat-table in Angular

I'm encountering an issue with the mat-table in my project. I want to incorporate squares into the cells, but I'm unsure how to achieve this. Here is a snippet of my current code: <div class="my_item"> <div><span class="s ...

Is it possible to modify the HTML element within a Blazor application simply by clicking a button?

Is it possible to dynamically change the type of an HTML element in a Blazor application by clicking a button? For example, turning normal text into input fields. In my table, there is a button in the first column for each entry. I want to make it so that ...

Develop an occurrence that hides one <div> element and generates a fresh <div> element in its place

I am in the process of designing an experiment with a web-based notepad. Currently, I have a textarea element that transfers its content to a hidden div when the HTML page is printed. However, I am facing an issue with the overflow of the textarea element. ...

The Astro loop feature fails to include any spacing when dividing a title

Currently, I am working on creating a Title component that accepts a text prop. This text is then split using the text.split(" ") JavaScript method to create an array of words. The component loops over this array and displays each word within the heading t ...

Is the progress bar able to duplicate itself?

I'm currently facing an issue with my progress bar, or as I like to call it, a depletion bar. The purpose of this bar is simple - whenever it's clicked, the button resets itself. However, if the bar reaches 100%, the player loses. The strange pro ...

The strict-origin-when-cross-origin policy is enforced when submitting a POST request through a form to a specific route

Currently, I am diving into the world of Node.js, express, and MongoDB by reading Greg Lims's book. However, I've hit a roadblock when trying to utilize a form to submit data to a route that should then output the body.title of the form in the co ...

An issue with the user agent is causing the HTML source data in the tag to become

Upon inspecting the URL code in Chrome, a message is displayed: Refused to set unsafe header "User-Agent" The site's code appears as follows: <div dir="auto" class="rn-13yce4e rn-fnigne rn-ndvcnb rn-gxnn5r rn-deolkf rn-cme181 rn-1471scf rn-14x ...

Issue with displaying the Bootstrap paginator stylingSomething seems to be

Currently, I am working on a PHP project that involves creating a table with Bootstrap styling. To achieve this, I referred to a tutorial which guided me through the process. After linking the necessary Bootstrap CSS file using the provided code snippet, ...

Determining User Login Status in Laravel using jQuery

While I am familiar with the authentication verification in laravel, I am interested in learning how to verify it using jQuery. Specifically, I want to make changes to my CSS when a user is logged in. By default: body{ background: url('image.jpg ...

Error encountered when trying to update Express Mongoose due to duplicate key

In my MongoDB database, I have a unique field called mail. When attempting to update a user, I encounter an issue where if I do not change the mail field, it triggers a duplicate key error. I need a solution where it is not mandatory to always modify the ...

How can I effectively transmit data using the AngularJs Sdk in the Loopback factory?

I am struggling with the following code snippet in my Angular factory: getPermissions: function(modelId){ var Pers = Permission.find({ filter : { where : { and : [ { user_id : $rootScope.userId ...

Tips for resolving the error of encountering a forbidden and unexpected token in JSON at position 0 while using React hooks

const [forecastData, setForecastData] = useState({ forecast: []}); useEffect(() => { let ignore = false; const FETCHDATA = async () => { await fetch(forecast,{ headers : { ...

Unable to establish a connection with the Mysql database using Node JS

My Class is responsible for handling a mysql connection, and every time I access the path /cargos, it should retrieve data and then close the connection. However, every time I try to Query, I encounter this error message: TypeError: conexao.query is not a ...

Tips for maintaining the integrity of blank space within a text node?

When intercepting a paste event and cleaning HTML off of the content using textNodes, I am faced with an issue where all white space is reduced to a single space and new lines are disregarded. For example, pasting: "hello world !" ends up being "h ...

What is the best way to reduce the spacing between text?

I am trying to figure out how to reduce the spacing between my text so that it aligns like the example below. Take a look at the text "Welcome to my portfolio". Currently, when I run my code, there is a large gap between "Welcome to my" and "Portfolio". ...

Adjust the size of the image file for uploading

I am attempting to restrict the file upload size to 1MB by using this jQuery code snippet : <td><label> Upload image </label> <input type="file" class="upload" name="image" value="<?php echo set_value('image'); ?>" ...

Display JSON values from a successful AJAX call within an HTML dropdown menu

Having an html form with multiple drop down selections, I have utilized the same form for data editing, To edit data in a specific row of the table, I implemented an AJAX request. Once a row is selected and the user clicks on edit, the AJAX call retrieves ...

How can I use VueJS and Vue Router to generate a details page for a list item?

I am currently working with a list of items sourced from a JSON file and looping through them. However, I want to create individual details pages for each item using VueRouter. Any advice on how I can accomplish this? I am facing difficulties in passing t ...

sending information stored in an array from an HTML form to PHP variables arranged in an array

I am currently facing an issue with a form designed to track the hours worked on various projects. The form features an array for project ID, hours, and notes fields, with the lines of the form iterating based on the number of projects. However, when passi ...