1

I simply want to translate some words globally. My translations are inside an object with the key as the original word and the value as the translation. However I can't get my function to work, what am I missing?

jQuery(document).ready(function() {
if (window.location.href.indexOf("sv") > -1) {
  var translations = {
    'All': 'alla',
    'Filter Members': 'Filtrera medlemar',
  }

  for (var key in translations) {
    if (translations.hasOwnProperty(key)) {
      console.log(key + " -> " + translations[key]);

      $allItems = jQuery("body *").children();

      $allItems.each(function() {
        $this = jQuery(this);
        $this.html().replace(key, translations[key]);
      });
    }
  }
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Carl Papworth
  • 1,282
  • 2
  • 16
  • 35
  • 2
    `jQuery("body *").children()` is an odd way of selecting nodes... If you want all nodes, just use `jQuery("body *")`. Also, you could just do `jQuery("body").html(jQuery("body").html().replace(key, translations[key]))`... then you wouldn't need to iterate through every node in the doc. Be careful with those translation keys though; if one of them is "span" or "class" or otherwise the same as an HTML element or attribute name, you'll cause some problems... – Heretic Monkey Apr 17 '19 at 14:57
  • 1
    Possible duplicate of [Replace text in HTML page with jQuery](https://stackoverflow.com/questions/4886319/replace-text-in-html-page-with-jquery) – Heretic Monkey Apr 17 '19 at 14:58

1 Answers1

0

You need to pass the new value to html() method. Strings are immutable calling function on them doesnot change the original string.

Second problem I see is that you are declaring global variables. You should use let or const

jQuery(document).ready(function () {
    if(window.location.href.indexOf("sv") > -1) {
      //CUSTOM TRANSLATIONS

     var translations = {
          'All' : 'alla',
          'Filter Members' : 'Filtrera medlemar',
     }



    for (var key in translations) {
    if (translations.hasOwnProperty(key)) {
        console.log(key + " -> " + translations[key]);

        const $allItems =  jQuery("body *").children();

        $allItems.each( function() {
            const $this = jQuery(this);
                $this.html($this.html().replace(key, translations[key]));

        });
    }
}
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73