Sometimes, we want to make HTML text clickable without making it a hyperlink with JavaScript.
In this article, we’ll look at how to make HTML text clickable without making it a hyperlink with JavaScript.
How to make HTML text clickable without making it a hyperlink with JavaScript?
To make HTML text clickable without making it a hyperlink with JavaScript, we can select the element with the text.
Then we set its onclick
property to a function that runs when we click on it.
For instance, we write:
<p>
hello
</p>
to add a p element.
Then we write:
const p = document.querySelector('p')
p.onclick = () => {
console.log('clicked')
}
to select the p element with document.querySelector
.
Then we set its onclick
property to a function that runs when we click on the p element.
As a result, we see the 'clicked'
is logged when we click on ‘hello’.
Conclusion
To make HTML text clickable without making it a hyperlink with JavaScript, we can select the element with the text.
Then we set its onclick
property to a function that runs when we click on it.