Determine the number of visible li elements using jQuery

Currently, I am utilizing a jQuery script to count the number of li elements in my HTML code. Here is an example of the setup:

HTML:

<ul class="relatedelements">
   <li style="display:none;" class="1">anything</li>
   <li style="display:none;" class="2">anything</li>
   <li style="display:none;" class="3">anything</li>
</ul>

jQuery:

    $(function() {
        var numrelated=$('.relatedelements > li').length;
        $('.num-relatedelements').html(numrelated); 
    });

The current output of this script is: 3

Sometimes, I modify the style="display: none" property of certain li elements using jQuery within $(document).ready. For instance, I may execute $('.2').show();.

Now, I am looking to adjust the script so that it only counts the visible li elements by adding :visible as specified in the jQuery documentation:

    $(function() {
        var numrelated=$('.relatedelements > li:visible').length;
        $('.num-relatedelements').html(numrelated); 
    });

The updated script currently outputs: nothing

I am uncertain why this modification isn't producing the desired result. If anyone has any suggestions or insights, I would greatly appreciate the assistance. Thank you in advance!

Answer №1

works perfectly for my project

$(document).ready(function(){
    $('.2').show();
    var numItems = $('.related-elements > li:visible').length;
    $('.num-related-elements').html(numItems); 
});​

Check out the JsFiddle Link : http://jsfiddle.net/qwerty/3/

Answer №2

Everything is functioning correctly in this instance:

http://jsfiddle.net/username/example/ (1 displayed element)

http://jsfiddle.net/username/example/1/ (0 displayed elements)

It's worth noting that utilizing numbers as class identifiers is considered unlawful. (W3C Regulation, bullet 2) Class names are required to commence with a letter. It's plausible that manipulating this could be causing complications?

Aside from that, I can only speculate that the issue lies elsewhere. Have you ensured you are utilizing the most up-to-date version of jQuery? (Although during my evaluations, it performs well even on versions dating back to 1.3, after which it ceases working entirely)

Is it possible that you have misspelled "displayed" in your actual code? (I've made this mistake in the past)

Answer №3

Items are considered hidden if they or their parent elements do not occupy any space in the document. This is determined by layout, not CSS visibility.

Preview:

<ul class="relatedelements">
   <li class="1 hidden">anything</li>
   <li class="2 hidden">anything</li>
   <li class="3 hidden">anything</li>
   <li class="4">anything</li>
    <li class="5">anything</li>
    <li class="6">anything</li>
    <li class="7 hidden">anything</li>
</ul>

<div class="num-relatedelements"></div>

CSS

.hidden {
    display: none;
}​

JavaScript

$(function() {  
   var numRelated = $('.relatedelements > li:not(.hidden)').length;
   alert(numRelated);
   $('.num-relatedelements').html(numRelated); 
});​

I have created a jsfiddle for your reference: http://jsfiddle.net/mgrcic/3BzKT/3/

Answer №4

This is how it functions:

$(function() {
    var visibleItems=$('.relatedelements > li:visible').length;
    $('.num-relatedelements').html(visibleItems); 
});

For a demonstration of this in action, click here.

Answer №6

Indeed, just as others have mentioned, it functions properly even after displaying the element in document.ready:

http://jsfiddle.net/bKyt4/

Answer №7

The reason your script is not returning anything is because all DIV's are currently hidden. It will only return a value of 1 when a specific element is shown.

Answer №8

I experimented with this approach and it appears to be effective, as I am receiving a result of '1'.

$(function() {
    $('.2').display();

    var numConnections=$('.connectedElements > li:visible').length;
    $('.num-connectedElements').html(numConnections); 
});

Note: I believe using numerical values for attributes may not adhere to proper markup guidelines.

Answer №9

To start, create a div, span, or paragraph in the desired location to show the count. Next, add a ul element with li items.

 $('.notification').html(
 $('#ul-alerts li').length);

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

An unusual html element

During a recent exploration of a website's code using the inspect tool, I stumbled upon a tag that was completely unfamiliar to me. <gblockquote></gblockquote> I've come across a blockquote before, but never a gblockquote. Interest ...

Modify a section of an HTML text's formatting

function changeEveryCharColor(id) { var part; var whole = ""; var cool1 = document.getElementById(id).innerHTML; console.log(cool1); for(var i = 0; i < cool1.length; i++) { color1 = getRandomInt(255); ...

Tips for resolving conflicts between CSS files

My index.html file contains multiple css and js files, including MaterializeCSS and a style.css file. However, when both are included simultaneously, using elements from Materialize such as tabs results in them not appearing correctly. Despite initializing ...

Exploring the contents of a JSON object

Just getting started with jquery and I'm attempting to parse a JSON object. This is my Jquery ajax call $(document).ready(function () { var resource = "v1/projects"; var url = '@Url.Action("Proxy")?resource=' + resource; ...

Alter numerous classifications based on varying circumstances at regular intervals

This code snippet is designed to change randomly all the <div class="percentx"> elements, for example from <div class="percent31"> to <div class="percent52"> (with values between 1-100). It works smoothly. I ...

Having trouble using jQuery to target the element "(this)"?

Currently, I am delving into jQuery and have stumbled upon a section that perplexes me. Due to my lack of familiarity with the terminology, conducting an effective Google search has proven difficult. Therefore, I decided to craft this question to elucidate ...

Maintain saved states upon page load/refresh using jQuery Cookies

I'm currently working on enhancing the accessibility features of a website. To achieve this, I have integrated three toggle buttons - one for adjusting font size, another one for highlighting links, and the third one for inverting colors. My objective ...

Solution to trigger CSS :hover to refresh following a transition (such as expanding a menu)

While there are existing discussions on this topic, I am presenting my query for two specific reasons: It introduces a potential alternative solution The demo code could be helpful to individuals looking to emulate a menu Following a CSS transition, the ...

Restore the initial content of the div element

Currently, I am utilizing the .hide() and .show() functions to toggle the visibility of my page contents. Additionally, I am using the .HTML() function to change the elements inside a specific div. $('#wrap').html(' <span id="t-image"> ...

Unable to extend the data-toggle dropdown to the entire width of the screen

Is there a way to make my navbar dropdown menu expand to the full width of the screen without leaving white space on the left side? I am using Bootstrap and have included a media query in my CSS as shown below. https://i.sstatic.net/US3ce.png <nav clas ...

Troubleshooting the lack of functionality with justify-items in CSS Grid

I'm facing an issue with my CSS Grid. I am attempting to set the justify-items property to start. Despite referencing the specification and watching a tutorial where it works, the property (and related ones) are not functioning as expected. In my tex ...

Dynamic elements fail to trigger JS function calls

I have a <div> that I dynamically populate with <input> and <a> elements using jQuery. It looks like this: The <div> gets filled when the addServicePanel() function is called: function addServicePanel() { var wrapper = $(".m ...

Implementing a Basic jQuery Animation: How to Easily Display or Conceal DIV Elements Using fadeIn and fadeOut

SCENARIO: Include 2 links, MY INFO and LOG IN, within a list of ul, li elements. Hovering over one link should display a box with a form inside using the fadeIn animation. The other link should show a button in a box with a fadeIn animation when hovered o ...

What could be causing the Javascript Dynamic HTML5 Table to not display on the page?

I have a program that calculates the total price of products based on a specified quantity and updates an HTML table with these values. To demonstrate this, I am constantly taking input using an infinite loop. <!DOCTYPE html> <html> ...

implement a click event handler for GLmol (webGL)

Check out GLmol, a Molecular Viewer built on WebGL and Javascript by visiting You can see a demo of GLmol in action at I am interested in adding a click function to GLmol. For example, when I click on a ball, I would like to retrieve information about it ...

Converting HTML into an object using $compile

I am currently working on calling an HTML template and want to bind the data with Angular. I successfully retrieve the data to bind and the HTML, but when I try to compile it, it returns all the HTML binded as an object. How can I convert it back to plain ...

Incrementing the image name by 1 each time a new image is added to the directory

Currently honing my PHP skills and in the learning process. Developed a simple script that enables users to upload images to a directory on the server. I aim to append a number at the end of each image name to prevent duplication. Here is my attempt at i ...

What is the correct way to create a template form in Django given the structure of my views.py file?

def ajax_lookup(request,channel): This particular view is essential for handling autocomplete functionality. The issue here lies in the JS code where an error occurs due to sending 1 attribute instead of the required 2. How can I successfully send the se ...

Tips for preventing Razor from interpreting special characters as HTML code

I'm encountering an issue with special characters displaying as HTML codes on the page I'm working on. The content is retrieved from a database and shown in readonly input boxes. For example, & is displayed as &. How can I ensure that the ...

Executing multiple ajax calls and retrieving the results: A step-by-step guide

I am looking to run a series of Ajax calls and collect the responses before rendering the results for the user. The current code I am using is not working as expected because the render function is being executed before all the Ajax responses have been ga ...