PDA

View Full Version : How to get the number of elements with a non-empty class name



Rain Lover
05-25-2019, 08:35 AM
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 (https://jsfiddle.net/Mori/dk8r1bx9/)

What I get: 4
What I expect: 2

keyboard
05-25-2019, 09:54 AM
Hey Rain Lover.
I saw your SO post, and my personal preference is definitely this solution -

console.log(document.querySelectorAll("p[class]:not([class=''])").length);
Just adding it in here in case anyone else stumbles into this thread.

coothead
05-25-2019, 10:30 AM
Hi there Rain Lover,



try it like this...


https://jsfiddle.net/nLfeucqh/

...for the empty ones. ;)



coothead