Is it possible to fill <h1 id="fillname"></h1>
with "John" or anything if I add ?fillname=John
or ?fillname=anythingausertype
in my URL?
Eg.: https://www.example.com/?fillname=John
fills <h1 id="fillname">John</h1>
Is it possible to fill <h1 id="fillname"></h1>
with "John" or anything if I add ?fillname=John
or ?fillname=anythingausertype
in my URL?
Eg.: https://www.example.com/?fillname=John
fills <h1 id="fillname">John</h1>
You should use window.location.search
and the URLSearchParams
helper object to look at URL parameters in JavaScript:
<html>
<head>
<title>Title of the document</title>
</head>
<body>
<h1>No parameters provided</h1>
<script>
var h1 = document.querySelector('h1');
var urlParams = new URLSearchParams(window.location.search);
if(urlParams.has('fillname')) {
h1.innerText = urlParams.get("fillname");
}
</script>
</body>
</html>
Try this in a browser and add '?fillname=test' to the end of the filename in the address bar.
Without any external library
const query = window.location.search.replace("?", "");
const parts = query.split("&");
const fillNameQS = parts[parts.findIndex(qs => qs.includes("fillname"))];
const value = fillNameQS.split("=")[1];
document.getElementById("#fillname").innerText = value;
You can, but i do not think this is a good idea. I think there are better ways to accomplish what you want.
Do do this, first get the parameter:
var url = new URL(window.location.href);
var fillname = url.searchParams.get("fillname");
then add it to the h1 tag:
document.getElementById("fillname").innerHTML = fillname;
References:
Use split
to separate and create array
const url = "https://www.example.com/?fillname=John";
const param = url.split('?')[1].split('=');
console.log(`<h1 id="${param[0]}">${param[1]}</h1>`)
Reference: Split
uri = window.location.search.split('=')
if (uri[0] === '?filename'){
document.getElementById('fillname').innerText = uri[1]
}