Results 1 to 4 of 4

Thread: test for presence of a div

  1. #1
    Join Date
    Feb 2007
    Posts
    36
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default test for presence of a div

    I am trying to create a link that will go to one location on a page by default, and another if a particular div is present.
    The script below works. But have I missed anything? Or is this really the right way to do it?
    Thanks in advance.


    Code:
    <html>
    <body>
    
    <div>
    
    <div id="special"></div>
    
    <a name="special">Special location</a>
    
    <p>
    <a name="default">Default</a>
    
    
    <p>
    <script>
    var special= document.getElementById('special');
    </script>
    <a href="#default" onclick='if (special) {window.scrollTo(0,special); return false;}'>click here</a>
    <p>
    
    
    <p>lorumipsum<p>lorumipsum<p>lorumipsum<p>lorumipsum<p>lorumipsum<p>lorumipsum<p>lorumipsum<p>lorumipsum<p>lorumipsum<p>lorumipsum<p>lorumipsum<p>lorumipsum<p>lorumipsum<p>lorumipsum<p>lorumipsum<p>lorumipsum
    
    <script>
    var special = document.getElementById('special').offsetTop;
    </script> 
    
    </div>
    </body>
    </html>

  2. #2
    Join Date
    Feb 2007
    Posts
    116
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    I would just use

    Code:
    <script type="text/javascript">
    var link = document.getElementById("special") ? "#default" : "#special";
    document.write('<a href="' + link + '">click here</a>');
    </script>
    and get rid of the other two scripts.

    Also, you need to close all those <p> tags.

    For example,

    Code:
    <p>This is a paragraph</p>
    <p>This is another paragraph</p>
    is valid, but

    Code:
    <p>This is a paragraph
    <p>This is another paragraph
    is not.
    "Rock and roll ain't noise pollution." - AC/DC

    http://www.blake-foster.com

  3. #3
    Join Date
    Feb 2007
    Posts
    36
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default

    Thanks for the alternative. I think I tried to put too much in my code. What I was actually looking for was to find out if this is the right way to see if a div is present. (ie make it a variable, then just use an "if" statement that says if the variable is there, do something)


    Code:
    <html>
    <body>
    
    <div id="specialdiv">This is the special div</div>
    <p>
    <script type="text/javascript">
    var special= document.getElementById('specialdiv');
    if (special) {document.write("The special div is there");}
    </script>
    </p>
    
    </body>
    </html>

  4. #4
    Join Date
    Feb 2007
    Posts
    116
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    Sure, that works.
    "Rock and roll ain't noise pollution." - AC/DC

    http://www.blake-foster.com

Bookmarks

Posting Permissions

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