+ 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
9 odpowiedzi
+ 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
+ 2
Small c @ console
+ 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.
+ 1
Works fine ,maybe you are getting some other error which you aren't telling about!
+ 1
you can use queryselectorall for that
+ 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;
+ 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
+ 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