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

Sample code:

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

  <title>Get elements number</title>

  <p class="">Hello, world!</p>
  <p class="5">Hello, world!</p>
  <p class="9">Hello, world!</p>
  <p class="">Hello, world!</p>



What I get: 4
What I expect: 2

1 Like

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.


This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.