how to count the links inside a <div>?

Discussion in 'JavaScript' started by aayybb, Jul 10, 2008.

  1. #1
    <div id="xxx">

    <a href= .......></a>
    <a href=........></a>
    <a href=........></a>

    </div>


    How can we find out how many links inside of this <div>?
    I know document.links.length will give me the number of the all the links in the page. But I don't know how to count them inside a <div>. If there is a way, I would also like to know how to refer each individual link so I can modify it.
     
    aayybb, Jul 10, 2008 IP
  2. rohan_shenoy

    rohan_shenoy Active Member

    Messages:
    441
    Likes Received:
    20
    Best Answers:
    0
    Trophy Points:
    60
    #2
    <html>
    <head>
    <script type="text/javascript">
    function countLinks()
    {
    var container=document.getElementById("mydiv");
    var linksInContainer=container.getElementsByTagName("a");
    alert(linksInContainer.length);//alerts no of links in the container
    }
    </script>
    </head>
    <body>
       <div id="mydiv">
          <a href="http://www.google.com">Google</a>
          <a href="http://www.yahoo.com">Yahoo</a>
          <a href="http://www.msn.com">MSN</a>
       </div>
    </body>
    </html>
    HTML:
     
    rohan_shenoy, Jul 10, 2008 IP
  3. aayybb

    aayybb Peon

    Messages:
    128
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thank you very much. It is exactly what I want. Thanks again.
     
    aayybb, Jul 10, 2008 IP