How to force Google Translate to translate text between and tags on my webpage? [closed]

1 week ago 17
ARTICLE AD BOX

How do I force Google Translate to translate text inside <code> tags on my webpage?

I read online that the <code tag can be replaced with a <span tag and then reverted after allowing google translate to translate that text but I don't know how to replace the tag after the translation (but the translation is done)

I tried using the following code snippet first (without replacing the <code tag with <span):

Javascript

<div id="google_translate_element"></div> <script type="text/javascript"> document.addEventListener('DOMContentLoaded', function() { // Get a reference to the code element const codeElement = document.getElementById('myCodeElement'); // Change the translate attribute to "yes" if (codeElement) { codeElement.setAttribute('translate', 'yes'); console.log("Translate attribute changed to 'yes'."); } else { console.log("Element with ID 'myCodeElement' not found."); } function googleTranslateElementInit() { new google.translate.TranslateElement({pageLanguage: 'en'}, 'google_translate_element'); }

HTML

<p style="font-family: &quot;verdana&quot;; font-size: 18px; color: black; line-height: 18px; text-align: justify; font-style: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; background-color: transparent;"><code id="myCodeElement" translate="no" style="background-color: transparent;"><strong>Disclaimer</strong></code>:&nbsp;None of the above mentioned are being recommended or, "prescribed" for use by others.</p>

This javascript allows the translation by setting the attribute to span (replacing code with span) but no attribute reversal is happening after the Google translation (to change the span back to code):-

<div id="google_translate_element"></div> <script type="text/javascript"> // Store original content document.addEventListener('DOMContentLoaded', function() { var codeElements = document.querySelectorAll('code'); codeElements.forEach(function(element) { var span = document.createElement('span'); span.innerHTML = element.innerHTML; span.setAttribute('data-original-tag', 'code'); // Store original tag element.parentNode.replaceChild(span, element); }); // Initialize Google Translate here // new google.translate.TranslateElement({pageLanguage: 'en'}, 'google_translate_element'); }); function googleTranslateElementInit() { new google.translate.TranslateElement({pageLanguage: 'en'}, 'google_translate_element'); } function revertSpanAttribute() { // Find all span elements that have the 'data-original-tag' attribute set to 'code' var elements = document.querySelectorAll('span[data-original-tag="code"]'); // Iterate through the found elements for (var i = 0; i < elements.length; i++) { // Remove the specific attribute from each element elements[i].removeAttribute('data-original-tag'); } } </script>

This finally did it:-

<div id="google_translate_element"></div> <script type="text/javascript"> // 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'); // Copy attributes and content Array.from(code.attributes).forEach(attr => span.setAttribute(attr.name, attr.value)); span.innerHTML = code.innerHTML; // Insert new span before the code and remove the code code.parentNode.insertBefore(span, code); code.parentNode.removeChild(code); }); } // Function to revert <span> back to <code> function revertSpanToCode() { console.log("Reverting span to code..."); const spans = document.querySelectorAll('span'); spans.forEach(span => { // Ensure we only target spans that were part of our replacement logic if possible, // or ensure no other spans on the page are accidentally affected. // A better approach might be to add a specific class during the initial replacement. // For this general example, we assume we want to revert all spans back to codes (which might be too broad). // A safer way is using a specific marker class or ID. // Assuming we add a class 'translated-span' during replacement: 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); } }); } // Use MutationObserver to detect Google Translate completion const observerCallback = (mutationsList, observer) => { const htmlEl = document.documentElement; const isTranslated = htmlEl.classList.contains('translated-ltr') || htmlEl.classList.contains('translated-rtl'); if (isTranslated) { // Page has been translated console.log("Google Translate detected. Applying span replacements."); replaceCodeWithSpan(); // You might want to disconnect the observer once done if you don't need further dynamic updates // observer.disconnect(); } else { // Translation was likely reverted to original language console.log("Google Translate reverted or not active. Reverting code replacements if any."); revertSpanToCode(); } }; // Configuration for the observer: watch for attribute changes on the <html> element const observerConfig = { attributes: true, attributeFilter: ['class'], childList: false, characterData: false }; const observer = new MutationObserver(observerCallback); // --- Your existing Google Translate Element initialization code should be here --- // This part should be after the definition of the functions above. 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'); } // -------------------------------------------------------------------------------- // Start observing the <html> element for class changes (which the translator does) observer.observe(document.documentElement, observerConfig); </script> <script> jQuery(function ($) { var $window = $(window); var $buttonTop = $('.button-top'); $buttonTop.on('click', function () { $('html, body').animate({ scrollTop: 0, }, 400); }); $window.on('scroll', function () { if ($window.scrollTop() > 300) { // 300 is our threshold in pixels $buttonTop.addClass('button-top-visible'); } else { $buttonTop.removeClass('button-top-visible'); } }); });
Read Entire Article