On a wordpress website I’d like to display "button one" when the url doesn’t contain "/en/" path, and display "button two" when url contains "/en/".
The button’ html look like this:
<a href="https://www.google.com" class="microwidget-btn mini-button header-elements-button-1 show-on-desktop" >Button one</span></a>
<a href="https://www.yahoo.com" class="microwidget-btn mini-button header-elements-button-2 show-on-desktop" >Button two</span></a>
I’ve been trying many variations of this approach:
<script type="text/javascript">
if(window.location.href.indexOf("/en/") > -1) {
document.getElementsByClassName("microwidget-btn mini-button header-elements-button-1 show-on-desktop").style.display = 'none';
document.getElementsByClassName("microwidget-btn mini-button header-elements-button-2 show-on-desktop").style.display = '';
} else {
document.getElementsByClassName("microwidget-btn mini-button header-elements-button-1 show-on-desktop").style.display = '';
document.getElementsByClassName("microwidget-btn mini-button header-elements-button-2 show-on-desktop").style.display = 'none';
}
</script>
But nothing happen and in the console I get
Uncaught TypeError: document.getElementsByClassName(…)[0] is undefined
Thank you
>Solution :
You could use JavaScript to check if the url contains a specific language like so
document.addEventListener("DOMContentLoaded", function() {
if(window.location.href.indexOf("/en/") > -1) {
// en page
// Show button 2
document.getElementById('button-one').style.display = 'none';
document.getElementById('button-two').style.display = 'flex';
} else {
//Show button 1
document.getElementById('button-one').style.display = 'flex';
document.getElementById('button-two').style.display = 'none';
}
});
Please notice that I changed you html code. I added an id property and style tag with display: none as default
<a href="https://www.google.com" id="button-one" class="microwidget-btn mini-button header-elements-button-1 show-on- desktop" style="display:none" >Button one</span></a>
<a href="https://www.yahoo.com" id="button-two" class="microwidget-btn mini-button header-elements-button-2 show-on-desktop" style="display:none">Button two</span></a>