Count the number of elements in an array (JavaScript)
Counting the number of elements in an array in JavaScript.
The text content of the page heading is divided into substrings by blank space, put into an array, the number of its elements is counted and printed:
HTML code:
<div class="example"></div>
JavaScript code:
<script>
// Getting the number of elements
var number_of_elements = document.querySelector('h1').textContent.split(' ').length;
// Printing the result
var array = new Array();
array = document.querySelector('h1').textContent.split(' ');
document.querySelector('.example').innerHTML += '<b>Array: </b> ' + '<br /><br />';
array.forEach( function( element, index ) {
document.querySelector('.example').innerHTML += '<b>[ ' + index + ' ] </b>' + element + '<br />';
});
document.querySelector('.example').innerHTML += '<br />' + '<b>Number of elements: </b> ' + number_of_elements;
</script>
Browser support
- Windows
- Edge 12.0+
- Firefox 3.5+
- Google Chrome 1.0+
- Opera 10.0+
- Linux
- Firefox 3.5+
- Google Chrome 1.0+
- Opera 10.0+
- iOS
- Safari 2.0+
- Android
- Samsung Internet 1.0+
- Chrome Android 18.0+
- Firefox for Android 4.0+
- Opera Android 10.1+