Create a query string in a URL (for a link <a>)

532 Views Asked by At

I am trying to create a query string in a URL for a link. I can't find what is the problem, I tried a lot of thing but I always get an "undefined" for "urlCameras". thanks for your help !

const cameras = [{
  _id: "Camera 1"
}];
const linkProduct = document.getElementById("linkProduct");

let url = 'file:///D:/openclassrooms/projet5/orinoco/product.html';
let urlObj = new URL(url);
let params = new URLSearchParams(url.search);
let idCameras = cameras[0]._id;
let urlCameras = params.append("?id=", "idCameras");
linkProduct.href = urlCameras;
<a id="linkProduct">Click</a>

1

There are 1 best solutions below

1
On BEST ANSWER

Several things

  1. .append("?id=", "idCameras"); should be .append("id",idCameras) because
  • ? and = - searchParams handles that for you
  • don't quote the parameter variable
  1. You have too many vars - the URL has its own searchParams you can use

const cameras = [{
  _id: "Camera1"
}];
const linkProduct = document.getElementById("linkProduct");

let url = 'file:///D:/openclassrooms/projet5/orinoco/product.html';
let urlObj = new URL(url);
let idCameras = cameras[0]._id;
urlObj.searchParams.append("id", idCameras);
linkProduct.href = urlObj;
<a id="linkProduct">Click</a>