Home > database >  Replace html tag with new tag content
Replace html tag with new tag content

Time:12-08

The html tag for the page doesn't have lang=en attribute, I'm trying to add it to html tag, below is the code I did it but it replaces the whole html content instead of just adding lang=en to html.

window.addEventListener('load', function () {
    alert("It's loaded!")
    const cond = document.getElementsByTagName('html')[0]|| false;
    console.log(cond)
     if (cond) {
          $('html').each(function() {
              $(this).replaceWith($('<html lang="en">'));
          });
    }});

Also I tried below code but it doesn't work too, basically it gets html content and it appends with new html tag and content.

const htmlContent = $( "html" ).html();
    if (cond) {
        $('html').replaceWith('<html lang="en">'   htmlContent    '</html>');
    }

CodePudding user response:

The possible solution using vanilla JS might be.

document.querySelector('html').setAttribute("lang", "en")

CodePudding user response:

This is not the optimal way of doing that because it could cause events to be detached or other performance issues. It would be safer to do:

$('html').attr('lang', 'en')`

This way you are only adding an attribute, nothing else.

CodePudding user response:

Use the attr method.

$(this).attr("lang", "en");

CodePudding user response:

Based on your code, you can try with vanilla js:

<script>
let domHTML = document.getElementsByTagName('html')[0];
let lang = domHTML.getAttribute('lang');
console.log('lang: '   lang);
domHTML.setAttribute('lang', 'fr');
lang = domHTML.getAttribute('lang');
console.log('lang: '   lang);
</script>

See details about setAttribute and getAttribute about using this attribute methods.

  • Related