Reputation: 55
I have an requirement in JS where, i want to get the count of li element which has the same inner value. What is the best way to do it ? I know we can achieve this in Jquery easily using find and contains but i don't want to use jquery.
I want the length of li elements has the Same Value.
For Eg: Say i want to find out how many LI has the value 'A'.
Below is the JS i have tried, which i think is not the best cos if i have say around 10,000 LI then i will have to loop through all the elements get their values and check if its what i want or no, which will surely hit the performance.
Note : LI element is added runtime with their Value.
HTML
<ul class="s_1" id="ULE">
<li class="r1">A</li>
<li class="r1">A</li>
<li class="r1">B</li>
<li class="r1">A</li>
</ul>
JS
var LI = document.getElementsByClassName('r1');
var cnt = 0;
for(var i=0;i<LI.length;i+=1){
if(LI[i].innerHTML == 'A'){
cnt += 1;
}
}
if(cnt === 4)
alert('working good!!');
Upvotes: 2
Views: 416
Reputation: 782785
You don't have to search all <li>
in the document. getElementsByClassName
can be applied to an element, it will then only search within that element. So you can do:
var LI = document.getElementById('ULE').getElementsByClassName('r1');
You can also simplify this with querySelectorAll
:
var LI = docuement.querySelectorAll('#ULE .r1');
Upvotes: 1
Reputation: 7698
I don't think there is a better way to improve the performance. If you have nothing but the DOM to work with (e.g. if the data is from user input), and not the underlying data structure from which you created the data, AFAICT there is no other structure to collect all of the elements than into an array-type structure, which will then require O(n) time to check every element.
Rather than have a count target, which is therefore dependent on the amount of list elements, try instead a function to handle the data, which increases the convenience somewhat:
function isEveryElementEqual(nodeList) {
val = nodeList[0].innerHTML;
for (var i=1; i<nodeList.length; i++) {
if (nodeList[i].innerHTML !== val) return false;
}
return true;
}
var LI = document.getElementsByClassName('r1');
console.log(isEveryElementEqual(LI)); // Returns false with the above HTML
Upvotes: 2