So basically I'm a beginner in JavaScript and HTML and trying to play with functions call on JS that will edit my HTML file. Now, I'm trying to redirect users to different pages based on their type. I want to use "onload" function in order to determine the user type and edit the link according to the result.
HTML:
<body onload="what_user()">
<div id="result">zone</div>
</body>
JS file:
function what_user() {
var d = document.getElementById("result");
var user = ""; // get the user type
if (user == "") d.outerHTML = "<a href=" "admin_index.html" ">" "</a>";
else d.outerHTML = "<a href=" "admin_user.html" ">" "</a>";
}
I have some problems understanding how to call a function from HTML and use it on JS as well as return values.
Thanks in advance!!!
CodePudding user response:
Don't play with elements as string. Create an element and put it where you want.
function what_user() {
var d = document.getElementById("result");
let a = document.createElement('a')
a.text = 'zone'
var user = ""; // get the user type
if (user == "") a.href = 'admin_index.html'
else {
a.href = 'admin_user.html'
}
d.parentNode.removeChild(d);
document.body.appendChild(a)
}
<body onload="what_user()">
<div id="result">zone</div>
</body>