Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count elements length by name only not display none using javascript?

Tags:

javascript

How to count elements length by name only not display:none using javascript ?

i want to count elements length by getElementsByName only that not display:none using.

this below code, it's count all name="test[]" and it's alert 5

I want to count name="test[]" only not display none (result will be 3). How can i do that ?

<div name="test[]"></div>
<div name="test[]"></div>
<div name="test[]"></div>
<div name="test[]" style="display: none;"></div>
<div name="test[]" style="display: none;"></div>

<script>
var test = document.getElementsByName("test[]");
alert (test.length);
</script>

https://jsfiddle.net/Lp6sn3w4/

like image 704
robert lovely Avatar asked Jun 06 '26 16:06

robert lovely


1 Answers

You need to iterate over the nodes and check their styles. To easily iterate over the nodes, you need to first convert the NodeList (you get that back from getElementsByName) to a regular array. You can then filter by the display style value and get the length of the array:

var test = document.getElementsByName("test[]");
var nodes = Array.prototype.slice.call(test);

nodes.filter(function(node) {
  return node.style.display !== "none"
}).length
like image 200
Alex R Avatar answered Jun 09 '26 06:06

Alex R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!