How to Insert JavaScript in HTML href

In this tutorial, I will show you how easily you can insert JavaScript in href. I know the situations when you need to insert JavaScript in href=” “. Sometimes you need to pass JavaScript string or variable to HTML href. This post will help you to do that very easily.

You can also read,

Process form value in PHP using jQuery AJAX method

Get user’s Latitude and Longitude in JavaScript HTML5 Geolocation

Insert JavaScript in href Easily

Your main moto is to insert JavaScript in HTML href. There are plenty of methods. But as this is CodeASpeedy, we gonna provide the simplest method to that. Do you want to insert JavaScript in HTML href right?

SO why not you are thinking of creating a JavaScript, where you can print HTML element? Just like the same echo or print does in PHP.

Let’s just create a script and use document.write() function to echo out HTML.

See the below example,

<script type="text/javascript">
     var stringurl="http://170.187.134.184";
     document.write('<a href="'+stringurl+'">Click Here</a>');
</script>

Using JavaScript Variable in href with document.write()

You can see that I have used a variable to put the URL string in href. You can put the URL directly in document.write(). But as I am giving you an example, that’s why I have used a variable. Here the plus operator is used to concate my variable string with the HTML tag.

 

Leave a Reply

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