1
\$\begingroup\$

Some browsers were not showing text on my webpage in bold so I put some text that was between <span> tags between <code> tags which was then shown as bold text (if the CSS made it to). Now, to make Google translate translate that text, I automatically replaced code tags with span tags and reverted them after the translation by google translate using javascript.

I was able to force Google Translate to translate text between the opening and closing "code" tags on my webpage by replacing "code" with "span" and reverting it after the google translation, but it is not translating every such text; sometimes all such text remains untranslated. How to fix this?

// Function to replace <code> with <span> across the document
function replaceCodeWithSpan() {
    console.log("Replacing code with span...");
    const codes = document.querySelectorAll('code');
    codes.forEach(code => {
        const span = document.createElement('span');
        Array.from(code.attributes).forEach(attr => span.setAttribute(attr.name, attr.value));
        span.classList.add('translated-span');
        span.innerHTML = code.innerHTML;
        code.parentNode.insertBefore(span, code);
        code.parentNode.removeChild(code);
    });
}
function applyOriginalTagAttribute() {
        const spans = document.querySelectorAll('span.original-code'); 

        spans.forEach(span => {
            if (span.classList.contains('original-code')) {
                span.setAttribute('data-original-tag', 'code');
            }
        });
}
function revertSpanToCode() {
    console.log("Reverting span to code...");
    const spans = document.querySelectorAll('span');
    spans.forEach(span => {
        if (span.classList.contains('translated-span')) {
            const code = document.createElement('code');
            Array.from(span.attributes).forEach(attr => code.setAttribute(attr.name, attr.value));
            code.innerHTML = span.innerHTML;
            span.parentNode.insertBefore(code, span);
            span.parentNode.removeChild(span);
        }
    });
}
const observerCallback = (mutationsList, observer) => {
    const htmlEl = document.documentElement;
    const isTranslated = htmlEl.classList.contains('translated-ltr') || htmlEl.classList.contains('translated-rtl');

    if (isTranslated) {
        console.log("Google Translate detected. Applying span replacements.");
        replaceCodeWithSpan();
    } else {
        console.log("Google Translate reverted or not active. Reverting code replacements if any.");
        revertSpanToCode();
    }
};
const observerConfig = { attributes: true, attributeFilter: ['class'], childList: false, characterData: false };
const observer = new MutationObserver(observerCallback);
function googleTranslateElementInit() {
  new google.translate.TranslateElement({
    pageLanguage: 'en', // Set your original page language
    layout: google.translate.TranslateElement.InlineLayout.VERTICAL // Change this line
  }, 'google_translate_element');
    setTimeout(revertSpanToCode, 1000); // Adjust delay as needed
}
observer.observe(document.documentElement, observerConfig);
(function checkAndClearRefreshFlag() {
    if (localStorage.getItem('hasRefreshed') === 'true') {
        localStorage.removeItem('hasRefreshed');
        console.log('Page was refreshed once and the flag has been cleared.');
    }
})();
function revertTranslation() {
    var translatedSpans = document.querySelectorAll('span[data-original-tag="code"]');
    translatedSpans.forEach(function(span) {
        var originalTag = span.getAttribute('data-original-tag');
        var code = document.createElement(originalTag);
        code.innerHTML = span.innerHTML;
        span.parentNode.replaceChild(code, span);
    });
}
(function() {
  const RELOAD_FLAG = 'gt_reloaded_once';
  if (sessionStorage.getItem(RELOAD_FLAG) === 'yes') {
    sessionStorage.removeItem(RELOAD_FLAG);
    return;
  }

  const observer = new MutationObserver(() => {
    const html = document.documentElement;
    const isTranslated = html.classList.contains('translated-ltr') ||
                         html.classList.contains('translated-rtl');
    if (isTranslated) {
      sessionStorage.setItem(RELOAD_FLAG, 'yes');
      observer.disconnect();
      location.reload();
    }
  });

  observer.observe(document.documentElement, {
    attributes: true,
    attributeFilter: ['class']
  });
  setTimeout(() => {
    const html = document.documentElement;
    if (!sessionStorage.getItem(RELOAD_FLAG) &&
        (html.classList.contains('translated-ltr') || html.classList.contains('translated-rtl'))) {
      sessionStorage.setItem(RELOAD_FLAG, 'yes');
      location.reload();
    }
  }, 3000);
})();
<body>
  <div id="google_translate_element"></div>

  <p style=
  "font-family: 'Verdana', sans-serif; font-size: 18px; color: black; font-weight: bold;">
&#9776; <code class="original-code"
  style="background-color: transparent;">Menu</code>
  </p>
</body>

\$\endgroup\$
6
  • 2
    \$\begingroup\$ I suggest making your code a runnable stack snippet with sample <code> tags so we can click "Run" and see how it works. I also suggest adding some context for your use case. What benefit does this feature offer your users? \$\endgroup\$ Commented Dec 3, 2025 at 20:49
  • \$\begingroup\$ @ggorlen I tried to create a runnable stack snippet but I believe that there is an error in it. Can you please correct it? Please also answer the question above if you can \$\endgroup\$ Commented Dec 4, 2025 at 7:49
  • \$\begingroup\$ Looks like you have HTML in your JS section: SyntaxError: expected expression, got '<'". It turns out with localStorage, the snippet won't run in the sandbox anyway. Oh well. This could be mocked but probably too much work. Still open question: what's the purpose of this project? As a user, I've never wanted my <code> tags translated and I'm trying to imagine a scenario where that's useful. \$\endgroup\$ Commented Dec 4, 2025 at 7:52
  • \$\begingroup\$ @ggorlen Some browsers were not showing text on my webpage in bold so I put some text that was between <span> tags between <code> tags which was then shown as bold text (if the CSS made it to). Now, to make Google translate translate that text, I did the above (replace code tags with span tags and revert them after the translation by google translate) \$\endgroup\$ Commented Dec 4, 2025 at 8:10
  • 1
    \$\begingroup\$ You might want to clarify your original problem a bit, in a different setting (stack overflow, maybe), since this seems like a very unusual workaround for a strange issue. Which browsers, which page? Surely, there's a more straightforward solution. I'd also edit that context into the post. \$\endgroup\$ Commented Dec 4, 2025 at 8:21

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.