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"
            }
          ];


function translate(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;
   }
  }
 }
}
function translateTo(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>
<span class='translatable'>hello</span> 
<span class='translatable'>and</span> 
<span class='translatable'>welcome</span> 
<span class='translatable'>to English</span> :)
</p>
<select onchange='translateTo(this.value)'>
<option value='EN'>English</option>
<option value='AR'>Arabic</option>
<option value='ES'>Espain</option>
</select>

Solution 2:

jsfriddle

<script>
function translating_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"