faqts : Computers : Programming : Languages : JavaScript : Links

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

5 of 7 people (71%) answered Yes
Recently 2 of 4 people (50%) answered Yes

Entry

Is there a way to pop up an alert if a named anchor (requested by a link) does not exist on a page? I would like to be able to use this in debugging.

Jan 9th, 2002 07:29
David Blackledge, Todd Rowan,


All named anchors in a page are listed in the document.anchors array.  
Each of those entries includes a .name attribute to check against.
If you want to test the starting URL's anchor validity, extract it with:
var namedanchor = window.location.hash;
If you want to test the URL of a link in the same page onclick, you 
could extract the same thing from the onclick event with:
var namedanchor = this.hash;
this gets the specified anchor, including the hash mark (#).
You can then strip off the hash mark and compare it against every named 
anchor in the page (you will need to do this at the bottom of the page 
or in the onload event to make sure that all named anchors are listed in 
the anchors array)
var foundanchor = false;
if(namedanchor.length > 1) {
 namedanchor = namedanchor.substring(1);//strip off #
 for(var i = 0 ; i < document.anchors.length ; ++i) {
  if(document.anchors[i].name == namedanchor) {
    foundanchor = true;
    break;
  }
 }
}
if( ! foundanchor)
 alert("Anchor Not Found!");
David.
http://David.Blackledge.com