How can I count the number of elements with same class?

后端 未结 6 603
有刺的猬
有刺的猬 2020-11-29 03:11

I have a main div in my page with a specific id. Now some input elements of the same class are present in this div. So how can I count the number o

6条回答
  •  爱一瞬间的悲伤
    2020-11-29 03:39

    I'd like to write explicitly two methods which allow accomplishing this in pure JavaScript:

    document.getElementsByClassName('realClasssName').length
    

    Note 1: Argument of this method needs a string with the real class name, without the dot at the begin of this string.

    document.querySelectorAll('.realClasssName').length
    

    Note 2: Argument of this method needs a string with the real class name but with the dot at the begin of this string.

    Note 3: This method works also with any other CSS selectors, not only with class selector. So it's more universal.


    I also write one method, but using two name conventions to solve this problem using jQuery:

    jQuery('.realClasssName').length
    

    or

    $('.realClasssName').length
    

    Note 4: Here we also have to remember about the dot, before the class name, and we can also use other CSS selectors.

提交回复
热议问题