0

I am creating a html file called test.html. Using JavaScript, I have parsed a URL to obtain the parsed parameters.

The URL looks something like this (Example URL)

http://path.to.a.webserver/test.html?p1=welcome&p2=home

After parsing the values, I want to send the parsed values to an HTML img tag in the following format. When I hit the above URL, the values p1 and p2 gets parsed and img tag in the test.html file gets executed.:

<img src="http://example2.com/tiger.gif?p1={p1_parsed_value}&p2={p2_parsed_value}"

I have tried using document.getElementById. I'm not sure if it is right. How can I pass only those parsed URL values into the src of the img tag?

CoderPJ
  • 991
  • 6
  • 18
  • 41

3 Answers3

2
var img = document.querySelector("img");//select node

img.setAttribute("src",url);//set src attribute to required url
Bakhtiiar Muzakparov
  • 2,308
  • 2
  • 15
  • 24
1

you can use URL

var baseUrl = 'http://example2.com/tiger.gif';
var u = new URL('http://example.com/test.html?p1=welcome&p2=hello');

// u.search: ?p1=welcome&p2=hello
var newUrl = baseUrl  + u.search;
console.log(newUrl);

// or 
newUrl = baseUrl + '?p1=' + u.searchParams.get("p1") + '&p2=' + u.searchParams.get("p2")
console.log(newUrl);

//to display the image

document.body.innerHTML += '<img src="' + newUrl +'">';
ewwink
  • 18,382
  • 2
  • 44
  • 54
1
$('#test img').attr('src', function(index,`val`) {
    return val.replace("default.jpg", "dynamic.jpg");
});
xlm
  • 6,854
  • 14
  • 53
  • 55