Categories
JavaScript Answers

How to make HTML text clickable without making it a hyperlink with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *