1

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>

4 Answers 4

5

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"));
}
Sign up to request clarification or add additional context in comments.

1 Comment

thanks it is working, now i want to pick the length so to do it
2

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.

Comments

1

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?

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.