Switch Href Link Of Button, Depends On Website Language By Js
Solution 1:
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.
functionchangeLink(lang) {
var theLink = document.querySelector('.donate-now');
if (lang == 'en-EN') {
console.log('en-EN')
theLink.href = "https://usrussiacc.org/membership/";
} elseif (lang == 'ru-RU') {
console.log('ru-RU')
theLink.href = "https://usrussiacc.org/ru/glavnaja/chlenstvo/";
} else {
console.log('neither')
}
}
changeLink(document.documentElement.getAttribute("lang"))
<htmllang="en-EN"><head></head><body><ahref=""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).
functionchangeLink() {
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 listlet 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()
<htmllang="en-EN"><head></head><body><ahref=""class="donate-now">I'm a link</a></body></html>
Post a Comment for "Switch Href Link Of Button, Depends On Website Language By Js"