Reputation: 7971
i want to know length of a tags
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
function clickme(){
var x=document.getElementsByTagName('a');
for(i=0;i<x.length;i++) {
alert(x[i].length)
}
}
</script>
</head>
<body>
<a href="#" value="1">first</a>
<a href="#" value="2">second</a>
<a href="#" value="3">third</a>
<input type="submit" onclick="clickme()"/>
</body>
Upvotes: 1
Views: 104
Reputation: 1319
I'm confused, you've changed your original question code sample from:
<script type="text/javascript">
function clickme(){
var x=document.getElementsByTagName('a');
for(i=0;i<x.length;i++) {
alert(x[i].value) //<- "value" not a valid property on the anchor tag
}
}
</script>
to
<script type="text/javascript">
function clickme(){
var x=document.getElementsByTagName('a');
for(i=0;i<x.length;i++) {
alert(x[i].length) //<- "length" not a valid property on the anchor tag
}
}
</script>
If you're just trying to determine what the ordered number of that anchor tag itself is, you could just use "i" (and again - var it!):
<script type="text/javascript">
function clickme(){
var x=document.getElementsByTagName('a');
for( var i=0;i<x.length;i++) {
alert(i);
}
}
</script>
Or am I missing something that you're asking?
Upvotes: 1
Reputation: 1319
jfriend00 got that right.
I thought I'd also point out though that you might want to declare "i" either ahead of, or inline with your for. Otherwise you're using a global "i" that could have unexpected consequences elsewhere.
Upvotes: 1
Reputation: 3426
In this example, x[i]
is a anchor DOM Element object. It doesn't have a value property normally. However, if you want to use the property, you can access it via:
x[i].getAttribute('value');
Personally, I would use HTML5 data attributes and define the anchor like:
<a href="#" data-value"=1">one</a>
Then access the value via:
x[i].getAttribute('data-value');
If a HTML5 doctype is used, this will be valid.
Upvotes: 2
Reputation: 707328
Since value is not a standard property of a link, you will probably need to use .getAttribute("value")
:
var x = document.getElementsByTagName('a');
for (var i=0; i<x.length;i++){
alert(x[i].getAttribute("value"));
}
Upvotes: 5