Jordan1993
Jordan1993

Reputation: 822

Count the number of list elements on page that have an id attribute

I have a list and I want to count only the items in that list that have an id attribute. For example, this is my code:

<ul class="members-list">
  <li id="newmember1"></li> 
  <li id="newmember2"></li>
  <li data-empty-index="3"></li>
  <li data-empty-index="4"></li>
</ul>

The list counts how many members are associated with an account and a user can add and delete members themselves. When they add a member, they are given an id. I want to count the number of unused accounts they have, i.e. the list items here that aren't associated with an id (the bottom 2).

I have the following code already to count how many list items altogether:

var listOfMembers = $(".members-list").children();
var numberOfMembers = listOfMembers.length;

However I don't know how to get the ones that don't have an id, and separate them from the group? I'm not even sure if this is possible, but would really grateful for any pointers please :)

Upvotes: 1

Views: 81

Answers (4)

Carl Edwards
Carl Edwards

Reputation: 14434

Simple. This can be done using the :not selector combined with targeting all li's with an id attribute.

$(function() {
  var listItems = $('li:not([id])');

  console.log(listItems.get(), 'Number of elements: ' + listItems.length)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="members-list">
  <li id="newmember1"></li>
  <li id="newmember2"></li>
  <li data-empty-index="3"></li>
  <li data-empty-index="4"></li>
</ul>

Upvotes: 0

Mamun
Mamun

Reputation: 68943

You can use .find() with :not()

var listOfMembers = $(".members-list").find(":not(li[id])");
var numberOfMembers = listOfMembers.length;
console.log(numberOfMembers);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="members-list">
  <li id="newmember1"></li> 
  <li id="newmember2"></li>
  <li data-empty-index="3"></li>
  <li data-empty-index="4"></li>
</ul>

OR: You can use .filter() to filter out the elements not having an id attribute.

var listOfMembers = $(".members-list li").filter((_, el) =>  !$(el).attr('id'));
var numberOfMembers = listOfMembers.length;
console.log(numberOfMembers);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="members-list">
  <li id="newmember1"></li> 
  <li id="newmember2"></li>
  <li data-empty-index="3"></li>
  <li data-empty-index="4"></li>
</ul>

Upvotes: 0

Addis
Addis

Reputation: 2530

You can use querySelectorAll():

let count = document.querySelectorAll('ul li[id]').length;

Upvotes: 0

Amit Chauhan
Amit Chauhan

Reputation: 6879

this should work for you.

var listOfMembers = $(".members-list").find("li[id]")

Upvotes: 2

Related Questions