The following code is recording which keys are being pressed. If the two first keys match the two first characters in a link, those characters will be highlighted. (In this case, "li" from "link.")
let keys = []
document.addEventListener('keypress', event => {
keys.push(event.key)
console.log(keys)
const selector = 'a'
let text = keys.join('')
let element = [...document.querySelectorAll(selector)]
.find(elements => elements.textContent.includes(text))
if (keys.length === 2) {
if (!element) {
keys = []
return
}
element.textContent = element.textContent.replace(text, `<strong>$1</strong>`)
}
})
<a href="#">link</a>
I want to highlight the characters with <strong>
tags.
I was expecting this:
link
But I got this instead:
<strong>$1</strong>nk
Steps:
- Press "Run code snippet"
- Type
l
theni
.