I have a button on a website, I translated the text (using po and mo files), but the link is still only one. I'm trying to switch that depends on in what language website is open, but my code doesn't work. May anybody please help
function changeLink(document.getAttribute("lang")){
var theLink = document.querySelector('.donate-now');
if(document.getAttribute("lang") == 'en-EN'){
theLink.href="https://usrussiacc.org/membership/";
} else if(document.getAttribute("lang") == 'ru-RU'){
theLink.href="https://usrussiacc.org/ru/glavnaja/chlenstvo/";
}
}
First, I assume you are setting <html lang="en-EN">
.
<html>
is actually the Root Element of document. It needs to be retrieved as such; the easiest and quickest way is document.documentElement
(MDS documentation).
Using this, we call document.documentElement.getAttribute("lang")
to retrieve the lang="aa-AA"
attribute off the <html>
tag.
I've also cleaned up the function, and called it separately.
function changeLink(lang) {
var theLink = document.querySelector('.donate-now');
if (lang == 'en-EN') {
console.log('en-EN')
theLink.href = "https://usrussiacc.org/membership/";
} else if (lang == 'ru-RU') {
console.log('ru-RU')
theLink.href = "https://usrussiacc.org/ru/glavnaja/chlenstvo/";
} else {
console.log('neither')
}
}
changeLink(document.documentElement.getAttribute("lang"))
<html lang="en-EN">
<head></head>
<body>
<a href="" class="donate-now">I'm a link</a>
</body>
</html>
Although the above code is still not very scalable, or friendly. Below I've rewritten it, to make it more scalable and reusable. Also removed the need for an argument all together. Just add more lang/path pairs to listURI
, and it will automatically handle them. You could also put in a generic URI, in case the given language doesn't exist (never trust users).
function changeLink() {
let listURI = {
'en-EN': 'https://usrussiacc.org/membership/',
'ru-RU': 'https://usrussiacc.org/ru/glavnaja/chlenstvo/'
};// Scale support, by adding new languages and URIs to this list
let linkURI = listURI[document.documentElement.getAttribute("lang")];
if (linkURI != undefined) {
document.querySelector('.donate-now').href = linkURI;
console.log(linkURI)
} else {
console.log("LANGUAGE DOESN'T EXIST")
}
}
changeLink()
<html lang="en-EN">
<head></head>
<body>
<a href="" class="donate-now">I'm a link</a>
</body>
</html>