Emmanuel Akinfulubi

JavaScriptBasic

Read the current page's title and links in JavaScript

Beginner · 3 min read

Every web page has a title (the text on the browser tab), headings and links. Browser extensions, SEO checkers and accessibility tools all start the same way: they read the page and report what is on it. In this tutorial you will write a function that does a small version of that.

The function is called describePage. You give it a page's document, and it returns one line such as "Exercises" with 1 h1 and 4 link(s). You need to know what a function and an object are. The browser parts are explained from zero.

The document object

When JavaScript runs in a browser, the page is available as an object called document. It has properties you can read:

  • document.title is the title text.
  • document.body is the visible part of the page.
  • document.body.getElementsByTagName('a') finds every element with that tag name, here every link. The result has a length, which is how many were found.

The tag h1 is the main heading of a page, and a is a link.

A document that isn't there

Node, which runs JavaScript outside the browser, has no document at all. If your code uses it there, it crashes. Asking typeof document === 'undefined' is the safe way to find out whether it exists, because typeof doesn't crash on a name that was never defined.

There is a second trick in this exercise. Instead of reaching for the global document inside the function, you pass the document in as an argument. Then you can hand the function a pretend document, a plain object shaped like the real one, and check the answer anywhere.

Here is the exercise. Try it yourself first if you like, or follow the steps below.

2 Report what the page is showing

easy

Report the current window's contents. Adapted: the usual version calls window.print(), which opens a print dialogue and cannot be tested. This gathers the same information and returns it.

Stuck? Three hints, smallest first
  1. 1. document.title and document.body are the two things worth reporting.
  2. 2. Guard for the case where there is no document at all, so the function also works outside a browser.
  3. 3. typeof document === 'undefined' is the check.

Step 1: read the title

Start with the simplest part. Take the document as an argument and read its title.

Step 1

function describePage(doc) {
  return `"${doc.title}"`;
}
console.log(describePage({ title: 'Exercises' })); // "Exercises"

The object { title: 'Exercises' } stands in for a real document. The function can't tell the difference, because it only reads title.

Step 2: count headings and links

Now count the h1 and a elements in the body. To test this outside a browser, the stand-in needs a getElementsByTagName method too. Ours looks the tag up in a small table of counts.

Step 2

function describePage(doc) {
  const headings = doc.body.getElementsByTagName('h1').length;
  const links = doc.body.getElementsByTagName('a').length;
  return `"${doc.title}" with ${headings} h1 and ${links} link(s)`;
}

const fakeDoc = {
  title: 'Exercises',
  body: {
    getElementsByTagName(tag) {
      const counts = { h1: 1, a: 4 };
      return { length: counts[tag] ?? 0 };
    },
  },
};
console.log(describePage(fakeDoc)); // "Exercises" with 1 h1 and 4 link(s)

counts[tag] ?? 0 means "the count for this tag, or 0 if there isn't one". The ?? operator only falls back when the left side is null or undefined.

Step 3: handle the missing pieces

Step 2 breaks in three situations. Try them:

JavaScript

describePage(null); // TypeError: Cannot read properties of null (reading 'body')

A page can also have an empty title, or no body yet. Add a guard for each:

Step 3

function describePage(doc) {
  if (!doc) return 'no document available';
  const title = doc.title || '(untitled)';
  const headings = doc.body ? doc.body.getElementsByTagName('h1').length : 0;
  const links = doc.body ? doc.body.getElementsByTagName('a').length : 0;
  return `"${title}" with ${headings} h1 and ${links} link(s)`;
}

console.log(describePage(null));                      // no document available
console.log(describePage(undefined));                 // no document available
console.log(describePage({ title: '', body: null })); // "(untitled)" with 0 h1 and 0 link(s)

!doc is true for both null and undefined, so one check covers both. doc.title || '(untitled)' uses the fallback when the title is an empty string. doc.body ? … : 0 only asks the body for elements when there is a body.

Step 4: use the real document when there is one

In a browser you pass the real document. In Node you skip it. typeof makes that safe:

Step 4

const real = typeof document === 'undefined' ? 'not in a browser' : describePage(document);
console.log('real document:', real); // in Node: real document: not in a browser

Paste the same lines into your browser's console on any page, and you get that page's title and counts instead.

The full solution

Here is the complete answer, with the stand-in document and the real-document line at the end. Press Run to see the output. The checks underneath try an empty title and a page with three headings.

The answer

// The usual version is one line:
//
//   window.print();
//
// That opens the browser's print dialogue. It cannot be asserted, and running it
// here would interrupt your reading. So instead: gather what is on the page.

function describePage(doc) {
  if (!doc) return 'no document available';

  const title = doc.title || '(untitled)';
  const headings = doc.body ? doc.body.getElementsByTagName('h1').length : 0;
  const links = doc.body ? doc.body.getElementsByTagName('a').length : 0;

  return `"${title}" with ${headings} h1 and ${links} link(s)`;
}

// A stand-in document, so the function can be tested without a browser.
const fakeDoc = {
  title: 'Exercises',
  body: {
    getElementsByTagName(tag) {
      const counts = { h1: 1, a: 4 };
      return { length: counts[tag] ?? 0 };
    },
  },
};

console.log(describePage(fakeDoc));
console.log(describePage(null));

// In a real browser you would call it with the real thing:
const real = typeof document === 'undefined' ? 'not in a browser' : describePage(document);
console.log('real document:', real);

Output


      
5 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 5 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

5 checks

test('a page is described', describePage(fakeDoc), '"Exercises" with 1 h1 and 4 link(s)');
test('no document is handled', describePage(null), 'no document available');
test('a missing title falls back', describePage({ title: '', body: null }), '"(untitled)" with 0 h1 and 0 link(s)');
test('the counts are read from the document, not assumed', describePage({ title: 'Blog', body: { getElementsByTagName: (tag) => ({ length: tag === 'h1' ? 3 : 0 }) } }), '"Blog" with 3 h1 and 0 link(s)');
test('undefined is no document either', describePage(undefined), 'no document available');

Adapted: the usual version is just window.print(). Two habits worth taking from the rewrite: pass the document in rather than reaching for the global, which is what lets a stand-in be substituted in a test; and guard for its absence so the same function runs under Node.

Common mistakes

  • Using document directly inside the function. The function then only works in a browser and can't be tested with a stand-in.
  • Writing if (document) to check for a browser. In Node that line itself throws a ReferenceError. Use typeof document === 'undefined'.
  • Forgetting .length. getElementsByTagName returns a collection of elements, not a number.

Try it yourself

  1. Add a count of images (the img tag) to the line, and add img: 2 to the stand-in's counts.
  2. Change the wording so it says "1 link" for one and "4 links" for more, instead of "link(s)".
  3. Open any web page, open the browser console, paste in describePage and call describePage(document).

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.