+ 16

[ Solved ] How can I count the number of Elements present with particular class name in JavaScript ?

Html : <body> <div class="elem"></div> <div class="elem"></div> <div class="elem"></div> <div class="elem"></div> </body> JS : let elem = document.getElementsByClassName(" elem "); console.log(elem.length) ; // Not working please help

9th Jun 2020, 9:10 AM
DIVYANSHU 😸
DIVYANSHU 😸 - avatar
9 Antworten
+ 4
It shows 0 becoz becoz your html code is not loaded Here is the quick fix: https://code.sololearn.com/WqMt7nYHTW4A/?ref=app You can also put your code in <script>tag or just use that I have did Hope this help you DIVYANSHU KR 😺 bro
9th Jun 2020, 9:22 AM
Coder
Coder - avatar
+ 2
Small c @ console
9th Jun 2020, 9:14 AM
Charan Leo25
Charan Leo25 - avatar
9th Jun 2020, 9:15 AM
Charan Leo25
Charan Leo25 - avatar
+ 2
<body> <div class="elem1"></div> <div class="elem1"></div> <div class="elem2"></div> <div class="elem2"></div> <div class="elem1"></div> <div class="elem1"></div> </body> //so your code to count this should be like this var elementos = document.querySelectorAll(".elem1"); // then console.log(elementos.length); result should be 4 // in case you want to count the other elem2 // then you have to select (create another var elementos2 in this case) var elementos2 = document.querySelectorAll(".elem2"); console.log(elementos2.length); // the result will be 2 in this case remember that with query selector you got a node.list, not an array.
9th Jun 2020, 12:55 PM
Gonzalo Torres del Fierro
Gonzalo Torres del Fierro - avatar
+ 1
Works fine ,maybe you are getting some other error which you aren't telling about!
9th Jun 2020, 9:20 AM
Abhay
Abhay - avatar
+ 1
you can use queryselectorall for that
11th Jun 2020, 7:00 AM
Pawan Chhangani
Pawan Chhangani - avatar
+ 1
You can use jQuery for that here is an example: $('#main-div .specific-class').length Or you can also use vanilla js like: document.querySelectorAll('#main-div .specific-class').length;
12th Jun 2020, 8:44 AM
Ishan Shah
Ishan Shah - avatar
+ 1
Do it like this. <Body> <Div class="elem"></div> <Div class="elem"></div> <Div class="elem"></div> <Script> Var elem=document.getElementsByClassName("elem") Console.log=elem.length; </Script> </Body> Notice the script tags inside the body tags too
23rd Jun 2020, 12:14 PM
Vic Okeke
+ 1
<Body> <Div class="elem"></div> <Div class="elem"></div> <Div class="elem"></div> <Script> Var elem=document.getElementsByClassName("elem"); Console.log(elem.length); </Script> </Body> Notice the script tags before closing the body
23rd Jun 2020, 12:18 PM
Vic Okeke