I’m creating a language switch, and it became necessary to create links using JavaScript. Language versions of the sites are located on separate subdomains.
The problem is that when adding the links seem to stick together. I also tried it add through with innerHTML, but nothing worked either, although they write that before inserting it clears the previous HTML.
I need it to be like this : https://**fr.**example.com/ : but it turns out like this : https://example.com/https://**fr.**example.com/ (concatenation?)
let hostName = window.location.hostname;
let pathName = window.location.pathname;
let ruSummary = 'fr.' + hostName + pathName;
var a = document.createElement('a');
var linkText = document.createTextNode("FR");
a.appendChild(linkText);
a.href = ruSummary;
let dropDownContent = document.querySelector(".dropdown-content");
dropDownContent.appendChild(a);
.dropdown {
position: relative;
display: inline-block;
}
.dropbtn {
padding: 5px;
cursor: pointer;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
width: 140px;
}
.dropbtn {
width: 40px;
}
.dropbtn::after {
background: rgba(0, 0, 0, 0) url("https://cdn3.iconfinder.com/data/icons/google-material-design-icons/48/ic_keyboard_arrow_down_48px-16.png") no-repeat scroll center center;
content: "";
height: 16px;
position: absolute;
right: 0;
top: 7px;
width: 16px;
}
.dropdown-content a {
color: black;
padding: 2px 0 2px 5px;
text-decoration: none;
display: block;
}
.dropdown:hover .dropdown-content {
display: block;
}
<div class="dropdown">
<div class="dropbtn">EN</div>
<div class="dropdown-content">
</div>
</div>
I’m waiting for your answers, thank you.
2
Answers
You are creating a relative link, because it does not have any starting slashes. So it’s relative to your current domain and current document. What you want is a link to your new, language-dependent domain.
Try this instead:
You can even do like so, if you do some kind of local testing without https:
You need to put
https://
in the hyperlink.Without it html will just hang the href onto the current domain.