Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    May 2012
    Posts
    9
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Cool getElementBytagName

    By using this javascript method can we check an element with particular id is present or not?


    <html>
    <head>
    <script type="text/javascript">
    function getElements()
    {
    var x=document.getElementsByTagName("input");

    for(i=0;i<x.length;i++)
    {
    if(x[i].id== x1)
    {alert("its x1");}

    else
    {alert("notx1");
    }
    alert(x.length);
    }
    </script>
    </head>
    <body>

    <input id="x1" type="text" size="20" /><br />
    <input type="text" size="20" /><br />

    <input type="button" onclick="getElements()" value="How many input elements?" />

    </body>
    </html>

    Am a beginner in javascript

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,147
    Thanks
    203
    Thanked 2,547 Times in 2,525 Posts
    if(x[i].id== x1) // a literal must be in quotes "x1"


    Code:
    <script type="text/javascript">
    function getElements() {
    var x=document.getElementsByTagName("input");
    alert(x.length);
    
    for(i=0;i<x.length;i++) {
    if(x[i].id== "x1") {
    alert("input " + i + " is x1")
    }
    
    else {
    alert("input " + i + " is not x1");
    }
    }
    
    }
    </script>
    The way you have disposed your opening and closing braces is very confusing -
    it is recomemnded that you place the opening brace following the function, if, else, for, while, do, switch, and try statements on the same line and not on the following line. Apart from that every Javascript statement should be followed by a semi-colon. ; It is quite possible to disregard this advice, but if you do one day it will rise up and bite you in the undercarriage.

    BTW, when posting here please help us to help you by following the posting guidelines and wrapping your code in CODE tags. This means use the octothorpe or # button on the toolbar. You can (and should) edit your previous post.
    Last edited by Philip M; 05-17-2012 at 09:40 AM.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • Users who have thanked Philip M for this post:

    cicily (05-25-2012)

  • #3
    New to the CF scene
    Join Date
    May 2012
    Posts
    9
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Thank u very much phil it helped..


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •