Sheerwood John Caday
Sheerwood John Caday

Reputation: 229

how to insert variable values in link href using javascript?

just want to ask if how to add a variable in the href? for example this is the my javascript:

    <script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
    $( document ).ready(function() {
        function setLinkValue(value) {
            var numItems = $('[id^=site-]').length;

            for (i = 0; i < numItems; i++) { 
                var link = document.getElementsByClassName('site-link');
                link.href = link.href.replace('putNatsvarHere', value);
            }

        }

        //You would pass netsvar here
        setLinkValue('ExampleValue');

    });
</script>

I want to insert it into my a tag in href

<a href="http://websitelink.com/track/putNatsvarHere/pt?thumb_id=302&gn=pt&gi=01.jpg" id="site-link" class="title" target="_self">Exclusive February Sale!</a><br>

    <a href="http://websitelink.com/track/putNatsvarHere/pt?thumb_id=302&gn=pt&gi=01.jpg" id="site-link" class="title-link" target="_self">Sale!</a>
    <br>
    <a href="http://websitelink.com/track/putNatsvarHere/pt?thumb_id=302&gn=pt&gi=01.jpg" id="site-link" class="title-link pink-play" target="_self"> February Sale!</a>

Upvotes: 0

Views: 1598

Answers (1)

Drew Gaynor
Drew Gaynor

Reputation: 8472

You can just replace a segment in the URL with the value, and you don't even need jQuery to do it. See the working example below.

function setLinkValue(value) {
  var link = document.getElementById('site-link');
  
  link.href = link.href.replace('putNatsvarHere', value);
}

//You would pass netsvar here
setLinkValue('ExampleValue');
<a href="http://websitelink.com/track/putNatsvarHere/pt?thumb_id=302&gn=pt&gi=01.jpg" id="site-link" class="title-link pink-play" target="_self">Exclusive February Sale!</a>

You could call setLinkValue in this way:

var natsvar = getCookie("nats");
setLinkValue(natsvar);

To update multiple elements, you could use getElementsByClassName and loop through them.

function setLinkValue(link, value) {
  link.href = link.href.replace('putNatsvarHere', value);
}

var elements = document.getElementsByClassName('title-link');
var i = 0;

for (i = 0; i < elements.length; i++) {
  //You would pass netsvar here
  setLinkValue(elements[i], 'ExampleValue');
}
<a href="http://websitelink.com/track/putNatsvarHere/pt?thumb_id=302&gn=pt&gi=01.jpg" class="title-link pink-play" target="_self">Exclusive February Sale!</a>
<a href="http://example.com/putNatsvarHere/" class="title-link pink-play" target="_self">Another link</a>

Upvotes: 1

Related Questions