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

javascript
#1

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

What I get: 4
What I expect: 2

1 Like
#2

p[class] means “Every p and has a class.” You’re halfway there.

What you want is “Every p and has a class and that class is not the empty string.”

:not(selector) is a css selector for negating a value.

So, give it a try yourself, see if you can translate my sentence into code; the spoiler below contains the answer.

“p[class]:not([class=’’])” [note that the inner quotes must be single quotes if they’re contained within double quotes, or double quotes if they’re contained in single quotes. In other words, dont break your string by using the same quotes inside it.

Technically this post is about CSS selectors, so i’ve put it in the CSS category.

3 Likes