Emmanuel Akinfulubi

JavaScriptDOM

Highlight bold words on hover in JavaScript

Intermediate · 4 min read

Point at a "Key terms" link and every key term in the article lights up. Hover a name in a list and its spot on a map is marked. Effects like these all follow one pattern: when the pointer moves onto one element, change the look of some others, and change them back when it leaves.

In this tutorial you will highlight every bold word in a paragraph while a link is hovered, and make the same thing work for people using a keyboard. You should know basic HTML and have changed a style from JavaScript before.

The page

index.html

<p><a href="#" id="trigger">Hover here</a></p>
<p id="para">We have just started this <b>section</b> for the <b>users</b>
who want to work with various JavaScript <b>problems</b> and write scripts
online to test their JavaScript <b>skill</b>.</p>

Four words are wrapped in b tags. Those are the ones to highlight.

Finding many elements at once

getElementById finds one element. To find all the elements that match a CSS selector, use querySelectorAll. It returns a NodeList, a list of elements you can loop over with for...of or forEach.

You can call it on any element to search only inside that element. para.querySelectorAll('b') finds the b tags inside the paragraph and nowhere else.

Hover events come in pairs

When the pointer moves onto an element, it fires mouseover. When it moves off, it fires mouseout. Keyboard users never fire either of those. When they press Tab to reach the link, it fires focus, and when they move on, it fires blur.

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

12 Highlight the bold words on hover

fair

Hovering a link should highlight every bold word in a paragraph, and moving away should remove the highlight.

Stuck? Three hints, smallest first
  1. 1. querySelectorAll(‘b’) finds them all; loop over the result.
  2. 2. Pair mouseover with mouseout, or the highlight never leaves.
  3. 3. Add focus and blur as well, or keyboard users get nothing.

Step 1: find the bold words

Step 1

const para = document.getElementById('para');
const bolds = para.querySelectorAll('b');
console.log(bolds.length); // 4
console.log([...bolds].map((b) => b.textContent).join(', ')); // section, users, problems, skill

A NodeList has forEach but no map, so it is spread into an array with [...bolds] before map is used.

Step 2: one function to turn the highlight on or off

Write a single function that takes true or false, rather than two separate ones:

Step 2

const bolds = document.getElementById('para').querySelectorAll('b');
function paint(on) {
  for (const b of bolds) {
    b.style.backgroundColor = on ? '#fff3bf' : '';
    b.style.outline = on ? '2px solid #f0c000' : '';
  }
}
paint(true);
console.log(bolds[0].style.outline !== ''); // true
paint(false);
console.log(bolds[0].style.outline === ''); // true

on ? '#fff3bf' : '' means "if on is true use the yellow, otherwise use an empty string". An empty string removes the inline style, so paint(false) puts every word back the way it was. The checks compare with '' rather than with the exact outline text, because a browser may write the outline back in its own order, with the color as rgb(...).

Step 3: connect it to hover

JavaScript

const trigger = document.getElementById('trigger');
trigger.addEventListener('mouseover', () => paint(true));

Try this in a browser and the words light up. Then move the pointer away, and they stay lit forever. Nothing told them to turn off. Hover effects always need the second half of the pair:

Step 3

const trigger = document.getElementById('trigger');
const bolds = document.getElementById('para').querySelectorAll('b');
function paint(on) {
  for (const b of bolds) {
    b.style.backgroundColor = on ? '#fff3bf' : '';
    b.style.outline = on ? '2px solid #f0c000' : '';
  }
}
trigger.addEventListener('mouseover', () => paint(true));
trigger.addEventListener('mouseout', () => paint(false));
trigger.dispatchEvent(new Event('mouseover'));
console.log(bolds[3].style.outline !== '');  // true
trigger.dispatchEvent(new Event('mouseout'));
console.log(bolds[3].style.outline === '');  // true

dispatchEvent sends the event from code, which is how you can check both halves without a mouse.

Step 4: keyboard users too

So far, someone who uses Tab to move around the page reaches the link and sees nothing. Add the keyboard pair:

Step 4

const trigger = document.getElementById('trigger');
const bolds = document.getElementById('para').querySelectorAll('b');
function paint(on) {
  for (const b of bolds) {
    b.style.backgroundColor = on ? '#fff3bf' : '';
    b.style.outline = on ? '2px solid #f0c000' : '';
  }
}
trigger.addEventListener('mouseover', () => paint(true));
trigger.addEventListener('mouseout', () => paint(false));
trigger.addEventListener('focus', () => paint(true));
trigger.addEventListener('blur', () => paint(false));
trigger.dispatchEvent(new Event('focus'));
console.log(bolds[0].style.outline !== ''); // true
trigger.dispatchEvent(new Event('blur'));
console.log(bolds[0].style.outline === ''); // true

Four listeners, two pairs. The text of the paragraph never changes, and no elements are added or removed; only their style does.

The same effect in CSS

This particular effect can also be done with no JavaScript at all. CSS can do it when the link is a sibling that comes before the paragraph. On this page the link sits inside its own p, so you would move it out of that p first. Then this rule does the job:

CSS

#trigger:hover ~ #para b,
#trigger:focus ~ #para b {
  background: #fff3bf;
}

That keeps working even if your script fails to load. Reach for JavaScript when the highlight needs to stay on after the interaction ends, for example a class you add on click and leave there.

The full solution

The panel builds the paragraph, attaches all four listeners and fires each event in turn, counting how many words are highlighted. Its checks confirm none at rest, all four on hover and on focus, none again after mouseout and blur, and that the text is never changed. Press Run, then hover or Tab to the link in the live demo.

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

The answer

const words = ['section', 'users', 'problems', 'skill'];
const para = el('p', { id: 'para' }, [
  'We have just started this ', el('b', {}, 'section'),
  ' for the ', el('b', {}, 'users'),
  ' who want to work with various JavaScript ', el('b', {}, 'problems'),
  ' and write scripts online to test their JavaScript ', el('b', {}, 'skill'), '.',
]);
const trigger = el('a', { href: '#', id: 'trigger' }, 'Hover here');
document.body.appendChild(el('p', {}, trigger));
document.body.appendChild(para);

const bolds = para.querySelectorAll('b');

function paint(on) {
  for (const b of bolds) {
    b.style.backgroundColor = on ? '#fff3bf' : '';
    b.style.outline = on ? '2px solid #f0c000' : '';
  }
}

trigger.addEventListener('mouseover', () => paint(true));
trigger.addEventListener('mouseout', () => paint(false));
// A keyboard user never fires mouseover. Without these two they get nothing.
trigger.addEventListener('focus', () => paint(true));
trigger.addEventListener('blur', () => paint(false));

// querySelectorAll gives a NodeList: it has forEach, but not filter or map.
const highlighted = () => [...bolds].filter((b) => b.style.backgroundColor === '#fff3bf').length;

console.log('bold words found:', bolds.length, [...bolds].map((b) => b.textContent));
console.log('highlighted at rest:', highlighted());
fire(trigger, 'mouseover');
console.log('after mouseover   :', highlighted());
fire(trigger, 'mouseout');
console.log('after mouseout    :', highlighted());
fire(trigger, 'focus');
console.log('after focus       :', highlighted(), '<- keyboard users get the same');
fire(trigger, 'blur');
console.log('after blur        :', highlighted());

Output


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

15 checks

test('all four bold words are found', bolds.length, 4);
test('and they are the right words', [...bolds].map((b) => b.textContent), words);
test('nothing is highlighted at rest', highlighted(), 0);
test('mouseover highlights all of them', (() => { fire(trigger, 'mouseover'); return highlighted(); })(), 4);
test('an outline is added too', bolds[0].style.outline, '2px solid #f0c000');
test('mouseout removes the highlight', (() => { fire(trigger, 'mouseout'); return highlighted(); })(), 0);
test('and clears the outline', bolds[0].style.outline, '');
test('focus does the same as hover', (() => { fire(trigger, 'focus'); return highlighted(); })(), 4);
test('blur undoes it', (() => { fire(trigger, 'blur'); return highlighted(); })(), 0);
test('the text is never changed', para.textContent.includes('section'), true);
test('and no elements were added or removed', para.querySelectorAll('b').length, 4);
test('a paragraph with no bold words is handled', para.querySelectorAll('strong').length, 0);
test('a NodeList has forEach', typeof bolds.forEach, 'function');
test('but not map, so it must be spread', typeof bolds.map, 'undefined');
test('and it is not an array', Array.isArray(bolds), false);

Two pairs of listeners, not one. mouseover without mouseout leaves the highlight stuck on. And focus/blur alongside them is what stops this being mouse-only: a keyboard user tabbing to the link fires focus and never mouseover, so without those two the feature simply does not exist for them. The assertions check both routes.

Worth knowing that this particular effect needs no JavaScript at all. #trigger:hover ~ #para b, #trigger:focus ~ #para b { background: #fff3bf } does the same job in CSS, and it keeps working if the script fails to load. Reach for JavaScript when the state has to outlive the interaction — a class you toggle and leave on, for instance.

Common mistakes

  • Adding mouseover without mouseout. The highlight turns on and never turns off.
  • Leaving out focus and blur. Keyboard users never fire mouse events, so they get nothing.
  • Calling map on a NodeList. It has forEach but not map or filter. Spread it first: [...bolds].

Try it yourself

  1. Use classList.add('hl') and classList.remove('hl') instead of setting two styles, and put the colors in a CSS rule for .hl.
  2. Add a second link that highlights only the first two bold words.
  3. Make a click on the link keep the highlight on until the next click, using classList.toggle.

Keep practising

Newsletter

New writing, when it lands.

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