Results 1 to 3 of 3

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

  1. #1
    Join Date
    Nov 2009
    Location
    Isfahan, Iran
    Posts
    229
    Thanks
    46
    Thanked 1 Time in 1 Post

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

    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

  2. #2
    Join Date
    Mar 2011
    Posts
    1,919
    Thanks
    59
    Thanked 105 Times in 103 Posts
    Blog Entries
    4

    Default

    Hey Rain Lover.
    I saw your SO post, and my personal preference is definitely this solution -
    Code:
    console.log(document.querySelectorAll("p[class]:not([class=''])").length);
    Just adding it in here in case anyone else stumbles into this thread.

  3. The Following User Says Thank You to keyboard For This Useful Post:

    Rain Lover (05-26-2019)

  4. #3
    Join Date
    Nov 2006
    Location
    chertsey, a small town 25 miles south west of london, england.
    Posts
    1,380
    Thanks
    1
    Thanked 244 Times in 239 Posts

    Default

    Hi there Rain Lover,


    try it like this...


    ...for the empty ones.

    coothead
    ~ the original bald headed old fart ~

Similar Threads

  1. Disable <a class button if input fields empty
    By qwikad.com in forum JavaScript
    Replies: 2
    Last Post: 10-16-2015, 04:28 PM
  2. Replies: 2
    Last Post: 02-13-2011, 11:03 PM
  3. Add increment number to class?
    By gwmbox in forum JavaScript
    Replies: 2
    Last Post: 06-03-2010, 12:31 AM
  4. Replies: 2
    Last Post: 10-18-2007, 06:14 PM
  5. Get elements by class name
    By riptide in forum JavaScript
    Replies: 28
    Last Post: 04-23-2007, 04:21 PM

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •