Forum Moderators: open

Message Too Old, No Replies

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

         

Rain_Lover

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

10+ Year Member Top Contributors Of The Month



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

NickMNS

2:37 pm on May 25, 2019 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



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...]

lucy24

4:48 pm on May 25, 2019 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Heh. I was thinking of a match involving /./ or /\w/

Fotiman

11:35 pm on May 25, 2019 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



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);

NickMNS

12:20 am on May 26, 2019 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I like the .filter(), I need to remember that one.

Fotiman

12:36 am on May 26, 2019 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



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