Help - Search - Members - Calendar
Full Version: How to get the number of elements with a non-empty class name
HTMLHelp Forums > Programming > Client-side Scripting
RainLover
Sample code:

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
Christian J
You might use the :not pseudoclass:

CODE
document.write(document.querySelectorAll("p:not([class=''])").length);

but note that the above will also match the following cases:

CODE
<p class=" ">Hello, world!</p>
<p>Hello, world!</p>

However this combination seems to work (newer browsers only, of course):

CODE

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

<script>
document.write(document.querySelectorAll("p[class]:not([class='']):not([class=' '])").length); // "2"
</script>

You may still get a match for CLASS values consisting of two or more whitespaces though:

CODE
<p class="  ">Hello, world!</p>

You might strip all whitespace with the trim() method or regex, but then you probably can't use querySelectorAll:

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

<script>
var p=document.getElementsByTagName('p');
var count=0;
for(var i=0; i<p.length; i++)
{
    p[i].className=p[i].className.trim();
    if(p[i].className!='')
    {
        count++;
    }
}
document.write(count); // "2"
</script>
RainLover
QUOTE(Christian J @ May 25 2019, 06:19 AM) *

You might use the :not pseudoclass:

CODE
document.write(document.querySelectorAll("p:not([class=''])").length);



Great! ❤
P.S. Isn't there any button on this forum to thank answerers, mark a post as helpful or choose it as the best answer?
Christian J
You're welcome!

No, you must do it manually. tongue.gif
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2024 Invision Power Services, Inc.