Reputation: 47
I have this code in C#:
@foreach (var photo in photos){
<div class="comment1" id="many">
@photo.name
</div>
}
<input type="button" name="button" onclick="count()" />
And I want to know how many "photo.names's" there are, so I made this javascript
function count(){
var algo = document.getElementById("many");
alert(algo.length);
}
But for some strange reason it gives me "undefined". Why is it happening? I have the javascript on a separate file
Upvotes: 0
Views: 4272
Reputation: 387567
document.getElementById
, as the method name suggest, gets a single element, not multiple.
Ids in HTML are supposed to be unique; there should be only one element with an id. So getElementById
returns exactly that element.
If you want to mark multiple items, you should use a class name instead. You can then use document.getElementsByClassName
.
Upvotes: 1
Reputation: 1089
Why is it happening?
HTML elements do not have a length
property. If you're looking for the length of what the element contains you'd need to do this
document.getElementById("many").innerHTML.length;
Keep in mind that IDs should be unique to an element.
If you're looking for "how many" comments there are, you'd need to do the following
document.getElementsByClassName("comment1").length;
Classes don't need to be unique across elements and and element can have more than 1 class.
Upvotes: 3