How to get the number of elements with a non-empty class name |
How to get the number of elements with a non-empty class name |
RainLover |
May 25 2019, 03:36 AM
Post
#1
|
Advanced Member Group: Members Posts: 216 Joined: 16-November 09 Member No.: 10,346 |
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 |
May 25 2019, 06:19 AM
Post
#2
|
. Group: WDG Moderators Posts: 9,661 Joined: 10-August 06 Member No.: 7 |
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 |
May 26 2019, 12:37 AM
Post
#3
|
Advanced Member Group: Members Posts: 216 Joined: 16-November 09 Member No.: 10,346 |
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? This post has been edited by RainLover: May 26 2019, 12:39 AM |
Christian J |
May 26 2019, 05:22 AM
Post
#4
|
. Group: WDG Moderators Posts: 9,661 Joined: 10-August 06 Member No.: 7 |
You're welcome!
No, you must do it manually. |
Lo-Fi Version | Time is now: 27th April 2024 - 08:03 PM |