skip to Main Content

I’m trying to create a conditional styling on javascript by calling this line found before the head and body tag:

<html class="js" lang="en">

I need to create a condition if the lang === "en" will display an image I hid with english content on it. I also have lang="de" which is another image with deutsch content hidden too.

Both images are linked in an <a> tag and if the site is in english, the english image will appear once clicked, if it’s in german, the deutsch image will appear once the link is clicked. I had the link in modal to pop up the image once clicked.

Here’s the image html code:

<a>
    <p><img> English Image FAQs</p>
    <p><img> Deutsch Image FAQs</p>
</a>

I hope I’m making sense. Thank you

2

Answers


  1. Take a look at this, I guess this is what you want:

    const setLang = (lang)=> document.getElementsByTagName("html")[0].setAttribute("lang", lang);
    setLang(navigator.language.slice(0,2))
    .en, .de {
      display: none;
    }
    html[lang="en"] .en {
      display: block;
    }
    
    html[lang="de"] .de {
      display: block;
    }
    <a>
        <p class="en"><img src="https://via.placeholder.com/150?text=en"> English Image FAQs</p>
        <p class="de"><img src="https://via.placeholder.com/150?text=de"> Deutsch Image FAQs</p>
    </a>
    
    <a onclick="setLang('de')">de</a>
    <a onclick="setLang('en')">en</a>
    Login or Signup to reply.
  2. EDIT:

    CBroe suggestion in the commens is better, making use of the :lang selector.


    You don’t really need javascript to do this, since css is enough. You could do a little change to your markup, adding a class for the two different paragraphs (or maybe an helper class):

    <a>
        <p class="english-only"><img> English Image FAQs</p>
        <p class="deutsch-only"><img> Deutsch Image FAQs</p>
    </a>
    

    Then from css you could say:

    html:not([lang=en]) .english-only {
        display: none;
    }
    
    html:not([lang=de]) .deutsch-only {
        display: none;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search