Emmanuel Akinfulubi

JavaScriptDOM

Get a link's attributes (href, rel, target) in JavaScript

Beginner · 3 min read

Links carry more than an address. A rel="nofollow" tells search engines not to vouch for the page you link to, target="_blank" opens a new tab, and hreflang says which language the page is in. Scripts that check outgoing links, add tracking or open external links in a new tab all start by reading these attributes.

In this tutorial you will read five attributes from a link with JavaScript, and learn the difference between an attribute and a property, which trips up a lot of people. You need basic HTML and a little JavaScript.

Attributes, in plain words

An attribute is a name="value" pair written inside an HTML tag. Here is the link for this exercise:

index.html

<a id="site" type="text/html" hreflang="en-us" rel="nofollow"
   target="_self" href="https://emmanuelakbi.com/">emmanuelakbi.com</a>

It has six attributes: id, type, hreflang, rel, target and href. We want the last five.

getAttribute and hasAttribute

Every element has getAttribute(name). It returns the value exactly as it is written in the HTML, as a string. If the attribute isn't there, it returns null. Its partner, hasAttribute(name), answers true or false.

Here is the exercise. Try it first if you like, then follow the steps.

4 Read a link’s attributes

easy

Given <a id="site" type="text/html" hreflang="en-us" rel="nofollow" target="_self" href="https://emmanuelakbi.com/">, read all five attributes.

Stuck? Three hints, smallest first
  1. 1. getAttribute(name) returns the string as written, or null if absent.
  2. 2. Many attributes also exist as properties, and the property is not always the same string.
  3. 3. href is the clearest case: the attribute keeps what you wrote, the property is resolved to a full URL.

Step 1: read one attribute

Find the link by its id, then ask for an attribute by name.

Step 1

const link = document.getElementById('site');
console.log(link.getAttribute('rel'));    // nofollow
console.log(link.getAttribute('target')); // _self

Attribute names don't care about capital letters in an HTML page, so getAttribute('REL') finds the same one.

Step 2: read all five into an object

A function that returns an object keeps the five values together and gives each one a clear name:

Step 2

function getAttributes(element) {
  return {
    href: element.getAttribute('href'),
    hreflang: element.getAttribute('hreflang'),
    rel: element.getAttribute('rel'),
    target: element.getAttribute('target'),
    type: element.getAttribute('type'),
  };
}
const attrs = getAttributes(document.getElementById('site'));
for (const [name, value] of Object.entries(attrs)) {
  console.log(name, '->', value);
}
// href -> https://emmanuelakbi.com/
// hreflang -> en-us
// rel -> nofollow
// target -> _self
// type -> text/html

Object.entries turns the object into a list of [name, value] pairs, so one loop can print every one of them.

Step 3: a missing attribute gives null

The link has no download attribute. Ask for it anyway:

Step 3

const link = document.getElementById('site');
console.log(link.getAttribute('download'));              // null
console.log(link.getAttribute('download') === undefined); // false
console.log(link.hasAttribute('download'));              // false
console.log(link.hasAttribute('rel'));                   // true

It is null, not undefined. That matters if you write if (value === undefined): the check never matches. When all you want to know is "is it there?", hasAttribute is the clearest way to ask.

Step 4: attribute versus property

Many attributes also exist as properties on the element: link.href, link.rel, link.target. Usually the two agree. href is the famous case where they don't. Take a link written with a relative address:

HTML

<a id="rel" href="/about">a relative link</a>

In a browser, on a page at https://emmanuelakbi.com/learn:

JavaScript

const relative = document.getElementById('rel');
console.log(relative.getAttribute('href')); // /about
console.log(relative.href);                 // https://emmanuelakbi.com/about

The attribute is what the HTML says. The property is what the browser worked out the full address to be. Neither one is wrong; they answer different questions. Use getAttribute when you want the HTML as written, and the property when you want the address the link really goes to. The live demo prints both for a relative link.

The full solution

The panel builds the link, reads all five attributes, and checks null and hasAttribute for a missing one. It also removes rel to show it then reads as null. Press Run to see the output.

Live, in a real browser. Click it. Sandboxed to allow-scripts only, so it cannot reach this page.

The answer

const link = el('a', {
  id: 'site',
  type: 'text/html',
  hreflang: 'en-us',
  rel: 'nofollow',
  target: '_self',
  href: 'https://emmanuelakbi.com/',
}, 'emmanuelakbi.com');
document.body.appendChild(el('p', {}, link));

function getAttributes(element) {
  return {
    href: element.getAttribute('href'),
    hreflang: element.getAttribute('hreflang'),
    rel: element.getAttribute('rel'),
    target: element.getAttribute('target'),
    type: element.getAttribute('type'),
  };
}

const attrs = getAttributes(document.getElementById('site'));

for (const [name, value] of Object.entries(attrs)) {
  console.log(name.padEnd(9), '->', JSON.stringify(value));
}
console.log('an absent attribute:', JSON.stringify(link.getAttribute('download')), '<- null, not undefined');
console.log('hasAttribute is the presence test:', link.hasAttribute('download'));

Output


      
13 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 13 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

13 checks

test('all five are read', Object.keys(attrs).length, 5);
test('href', attrs.href, 'https://emmanuelakbi.com/');
test('hreflang', attrs.hreflang, 'en-us');
test('rel', attrs.rel, 'nofollow');
test('target', attrs.target, '_self');
test('type', attrs.type, 'text/html');
test('an absent attribute is null', link.getAttribute('download'), null);
test('which is not undefined', link.getAttribute('download') === undefined, false);
test('hasAttribute reports absence', link.hasAttribute('download'), false);
test('and presence', link.hasAttribute('rel'), true);
test('attribute names are case-insensitive', link.getAttribute('HREF'), 'https://emmanuelakbi.com/');
test('removing one makes it null', (() => { link.removeAttribute('rel'); return link.getAttribute('rel'); })(), null);
test('and hasAttribute agrees', link.hasAttribute('rel'), false);

getAttribute returns null for a missing attribute, not undefined. That matters because null == undefined is true but null === undefined is false, so a strict check against the wrong one silently never matches.

The bigger point is attribute versus property. For a link written as href="/about", getAttribute('href') gives back "/about" while the .href property gives the fully resolved "https://yoursite/about". Neither is wrong; they answer different questions. The live demo prints both for a relative link so you can see them differ. Use getAttribute when you want what the HTML says, and the property when you want what the browser resolved it to.

Common mistakes

  • Checking for undefined. getAttribute returns null for a missing attribute, so === undefined is never true.
  • Expecting .href to match the HTML. The property is a full, resolved address. Use getAttribute('href') for what was written.
  • Writing link.getAttribute.rel. getAttribute is a function. Call it with the name as a string: link.getAttribute('rel').

Try it yourself

  1. Use link.setAttribute('target', '_blank') to make the link open in a new tab, then read it back.
  2. Loop over every link on a page with document.querySelectorAll('a') and print the ones that have rel="nofollow".
  3. Remove the hreflang attribute with removeAttribute, then check what getAttribute and hasAttribute say.

Keep practising

Newsletter

New writing, when it lands.

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