Skip to content Skip to sidebar Skip to footer

How Can I Set A Label Text By A Javascript Function Without Knowing The Label Id In Javascript

I need to set the text of a HTML label with various language translations. I know how to do it when i know the ID of the label, but i want to make a general Javascript function whi

Solution 1:

var voc = [
            {
              "AR":"أهلا",
              "ES":"¡Hola",
              "EN":"hello"
            },
            {
              "AR":"مرحبا",
              "ES":"bienvenida",
              "EN":"welcome"
            },
            {
              "AR":"و",
              "ES":"y",
              "EN":"and"
            },
            {
              "AR":"في اللغة العربية",
              "ES":"a España",
              "EN":"to English"
            }
          ];


functiontranslate(ele,lng){
 for(var i=0;i<voc.length;i++){
  for(var k in voc[i]){
   if(voc[i][k] == ele.innerText.trim()){
    ele.innerText = voc[i][lng];
    break;
   }
  }
 }
}
functiontranslateTo(lng){
var trc = document.getElementsByClassName("translatable");
for(var i=0;i<trc.length;i++){
translate(trc[i],lng);
}
}
//add this function to any event button.click,select.change or on load//translateTo("AR");
<p><spanclass='translatable'>hello</span><spanclass='translatable'>and</span><spanclass='translatable'>welcome</span><spanclass='translatable'>to English</span> :)
</p><selectonchange='translateTo(this.value)'><optionvalue='EN'>English</option><optionvalue='AR'>Arabic</option><optionvalue='ES'>Espain</option></select>

Solution 2:

jsfriddle

<script>functiontranslating_function(str) {
  return'translating: ' + str;
}
</script><label><script>document.write(translating_function("hello")); </script></label>

Post a Comment for "How Can I Set A Label Text By A Javascript Function Without Knowing The Label Id In Javascript"