Kesaja
Kesaja

Reputation: 57

Change parameter value in script tag using JS/jQuery

so I am trying to change a value of a parameter using JS or jQuery. I have a url that looks like this:

www.exampleurl.com/somepage?foo=test

I already have the code for getting the value coming after foo which is:

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, '\\$&');
    var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

var foo = getParameterByName('foo');

I now have a page where the HTML-Code looks like this:

<div class="bonus-button">
    <script language="javascript" type="text/javascript" src="https://t.tellja.eu/widget/button/PSIGn2?skin=194&t_mc=kwk&btn=rec_somecompany"></script>
</div>

What I want to do is replace t_mc=kwk with t_mc=value.of.foo. In this example it would mean

<div class="bonus-button">
    <script language="javascript" type="text/javascript" src="https://t.tellja.eu/widget/button/PSIGn2?skin=194&t_mc=test&btn=rec_somecompany"></script>
</div>

So far I have not found something I could really use or that works. Do you guys have any suggestions what I could use, e.g. replace didn't work.

Upvotes: 0

Views: 955

Answers (1)

ellipsis
ellipsis

Reputation: 12152

Use document.querySelector to get the script tag and using getAttribute get the src from the script. In the string obtained using split and join replace the value and set the src again using setAttribute

var a = document.querySelector('.bonus-button > script').getAttribute('src')
document.querySelector('div > script').setAttribute('src', a.split('t_mc=kwk').join('t_mc=value.of.foo'))
<div class="bonus-button">
  <script language="javascript" type="text/javascript" src="https://t.tellja.eu/widget/button/PSIGn2?skin=194&t_mc=kwk&btn=rec_somecompany"></script>
</div>

Upvotes: 1

Related Questions