Welcome to WebmasterWorld Guest from 34.229.24.100

Forum Moderators: open

How to get the number of elements with a non-empty class name

     
8:33 am on May 25, 2019 (gmt 0)

Full Member

5+ Year Member Top Contributors Of The Month

joined:Mar 1, 2010
posts: 209
votes: 0


Sample code:

<!DOCTYPE html>
<html lang="en">

<head>
<title>Get elements number</title>
</head>

<body>
<p class="">Hello, world!</p>
<p class="5">Hello, world!</p>
<p class="9">Hello, world!</p>
<p class="">Hello, world!</p>
<script>
console.log(document.querySelectorAll("p[class]").length);
</script>
</body>

</html>


DEMO [jsfiddle.net]

What I get: 4
What I expect: 2
2:37 pm on May 25, 2019 (gmt 0)

Senior Member

WebmasterWorld Senior Member Top Contributors Of The Month

joined:Apr 1, 2016
posts:2626
votes: 774


What you get is correct based on the code, there are 4 p elements with the "class" attribute, however 2 of those have a className = "". There are two ways to fix this, either remove the empty class from the p elements in the html, which I assume is not a real option. Or, you need to use an if statement to check that the className is not "". I updated your fiddle with a solution.

[jsfiddle.net...]
4:48 pm on May 25, 2019 (gmt 0)

Senior Member from US 

WebmasterWorld Senior Member lucy24 is a WebmasterWorld Top Contributor of All Time 5+ Year Member Top Contributors Of The Month

joined:Apr 9, 2011
posts:15705
votes: 813


Heh. I was thinking of a match involving /./ or /\w/
11:35 pm on May 25, 2019 (gmt 0)

Senior Member from US 

WebmasterWorld Senior Member fotiman is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month

joined:Oct 17, 2005
posts: 5021
votes: 26


I would convert to an array and then use filter to get only the elements who's className is not empty:

const p = Array.from(document.querySelectorAll("p[class]"))
.filter(el => el.className);
12:20 am on May 26, 2019 (gmt 0)

Senior Member

WebmasterWorld Senior Member Top Contributors Of The Month

joined:Apr 1, 2016
posts:2626
votes: 774


I like the .filter(), I need to remember that one.
12:36 am on May 26, 2019 (gmt 0)

Senior Member from US 

WebmasterWorld Senior Member fotiman is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month

joined:Oct 17, 2005
posts: 5021
votes: 26


The array methods changed the way I write JavaScript: filter, map, and reduce especially.