Printable Version of Topic

Click here to view this topic in its original format

HTMLHelp Forums _ Client-side Scripting _ How to get the number of elements with a non-empty class name

Posted by: RainLover May 25 2019, 03:36 AM

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>


https://jsfiddle.net/Mori/dk8r1bx9/

What I get: 4
What I expect: 2

Posted by: Christian J May 25 2019, 06:19 AM

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>

Posted by: RainLover May 26 2019, 12:37 AM

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?

Posted by: Christian J May 26 2019, 05:22 AM

You're welcome!

No, you must do it manually. tongue.gif

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)