Log in

View Full Version : test for presence of a div



Peter Johnson
03-05-2007, 06:12 PM
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.




<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>

Blake
03-05-2007, 07:03 PM
I would just use




<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,



<p>This is a paragraph</p>
<p>This is another paragraph</p>


is valid, but



<p>This is a paragraph
<p>This is another paragraph


is not.

Peter Johnson
03-05-2007, 10:03 PM
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)




<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>

Blake
03-05-2007, 11:20 PM
Sure, that works.