Course outline · 0% complete

0/30 lessons0%

Course overview →

Links and images

lesson 2-3 · ~8 min · 5/30

Links

Links are the entire reason the web is called a web: they are what connect isolated documents into something navigable, and they are how search engines discover pages at all (crawlers literally follow a elements from page to page). A page nobody can link to effectively does not exist.

The a element (anchor) turns anything into a link. Its href attribute (you met attributes in lesson 2-1) holds the destination:

<a href="https://developer.mozilla.org">MDN docs</a>
<a href="/courses">Courses</a>
<a href="#pricing">Jump to pricing</a>

<h2 id="pricing">Pricing</h2>

Three kinds of destination:

  • Absolute URL: a full address starting with https://. Goes anywhere on the web.
  • Relative path: starts with / (or nothing). Stays on the same site.
  • Fragment: starts with #. An id is an attribute that gives one specific element a unique name on the page, like the id="pricing" on the h2 above. A fragment link scrolls to the element whose id matches, with no page load. (ids return in lesson 3-1 to pair labels with inputs, and in unit 4 as CSS selectors.)

Quiz

For <a href="#team"> to scroll somewhere when clicked, what must exist on the page?

Images

img is a void element (no closing tag, lesson 2-1) with two attributes you should treat as mandatory:

<img src="/photos/team.jpg" alt="Four students at a whiteboard">
  • src tells the browser where the image file lives (absolute or relative, exactly like href).
  • alt is a text description. Screen readers speak it, search engines index it, and the browser shows it when the image fails to load.

Write alt as if describing the photo to someone over the phone. Purely decorative images get an empty alt="", which tells screen readers to skip them. Omitting alt entirely is worse: many screen readers then read the file name out loud.

Quiz

The image loads perfectly. What does the browser do with its alt text?

Two tasks. 1) Turn the text MDN docs into a link to https://developer.mozilla.org. 2) Add an image with src="team.jpg" and a descriptive alt. That file does not exist in the sandbox, which is the point: watch the browser fall back to showing your alt text.

Code exercise · javascript

Pages often build links from data, and unsafe destinations (like javascript: URLs) must be rejected. Write link(text, url): if url starts with "https://" or "/", return the full anchor tag string. Otherwise return just the text with no tag.