Links

The links[] array of the Document object contains Link objects that represent each of the hypertext links in a document. Recall that HTML hypertext links are coded with the href attribute of the <a> tag. In JavaScript 1.1 and later, the <area> tag in a client-side image map also creates a Link object in the Document links[] array.

The Link object represents the URL of the hypertext link and contains all the properties that the Location object (introduced in Chapter 13) does. For example, the href property of a Link object contains the complete text of the URL to which it is linked, while the hostname property contains only the hostname portion of that URL. See the client-side reference section for a complete list of these URL-related properties.

Example 14-5 shows a function that generates a list of all the links in a document. Note the use of the Document write( ) and close( ) methods to dynamically generate a document, as discussed earlier in this chapter.

Example 14-5. Listing the links in a document

/*
 * FILE: listlinks.js
 * List all links in the specified document in a new window
 */
function listlinks(d) {
    var newwin = window.open("", "linklist", 
                             "menubar,scrollbars,resizable,width=600,height=300");

    for (var i = 0; i < d.links.length; i++) {
        newwin.document.write('<a href="' + d.links[i].href + '">')
        newwin.document.write(d.links[i].href);
        newwin.document.writeln("</a><br>");
    }
    newwin.document.close(  );
}

Links, Web Crawlers, and JavaScript Security

One obvious ...

Get JavaScript: The Definitive Guide, Fourth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.